Home > Net >  From total hours amount how to determine Date and Month
From total hours amount how to determine Date and Month

Time:12-06

Format is DD/MM/YYYY. And for example I will have an int number like 240. This number is total hours actually. Lets accept "01/01/2023 01:00" as a first hour(total hour 1) and "02/01/2023 01:00" as a 25. hour(total hour 24 1=25) from the year beginning. So what would be the date for 240.hours totally? In that case it should be formatted like 11/01/2023 01:00 but I couldn't figure out how to format that.

CodePudding user response:

Your question is a little confusing; I wasn't sure about what you were after, although I think I got it after reading the comments.

Try running this code; I think it will be a help to you.

using System;

DateTime d = DateTime.Now;

var lastMonth = d.AddMonths(-1);
var nextMonth = d.AddMonths(1);

var yesterday = d.AddDays(-1);
var tomorrow = d.AddDays(1);

// lod = length of day
TimeSpan lod1 = new TimeSpan(days: 1, hours: 0, minutes: 0, seconds: 0);
TimeSpan lod2 = new TimeSpan(days: 0, hours: 23, minutes: 59, seconds: 59, milliseconds: 1_000);

if (lod1 != lod2)
{
    Console.WriteLine($"This lne should not be seen; {nameof(lod1)}");
}

var tomorrow2 = d.AddDays(lod1.Days);

if (tomorrow != tomorrow2)
{
    Console.WriteLine($"This lne should not be seen; {nameof(tomorrow)}");
}

Console.WriteLine($"Tomorrow lives in the month of {tomorrow.Month} and will be day {tomorrow.Day} of that month.\n");

var periodOfTime = new TimeSpan(tomorrow.EndOfDay().Ticks - yesterday.StartOfDay().Ticks);

Console.WriteLine($"{periodOfTime.Days} days between yesterday and tomorrow.");

Console.WriteLine($"{periodOfTime.TotalDays} total days between yesterday and tomorrow.");

var someFutureDate = yesterday.AddDays(periodOfTime.Days);
var someFutureDate2 = yesterday.AddDays(periodOfTime.TotalDays);

Console.WriteLine();

Console.WriteLine($"1) Two {nameof(periodOfTime.Days)} after yesterday is:");
Console.WriteLine(someFutureDate.ToString("yyyy-MM-dd HH:mm:ss.fffff"));
Console.WriteLine(someFutureDate.DayOfWeek);

Console.WriteLine();

Console.WriteLine($"2) Two {nameof(periodOfTime.TotalDays)} after yesterday is:");
Console.WriteLine(someFutureDate2.ToString("yyyy-MM-dd HH:mm:ss.fffff"));
Console.WriteLine(someFutureDate2.DayOfWeek);

internal static class Extensions
{
    public static DateTime StartOfDay(this DateTime date) =>
        new(date.Year, date.Month, date.Day, 0, 0, 0, 0, date.Kind);

    public static DateTime EndOfDay(this DateTime date) =>
        new(date.Year, date.Month, date.Day, 23, 59, 59, 999, date.Kind);
}

Running this now, I get:

Tomorrow lives in the month of 12 and will be day 6 of that month.

2 days between yesterday and tomorrow.
2.999999988425926 total days between yesterday and tomorrow.

1) Two Days after yesterday is:
2022-12-06 17:05:52.55833
Tuesday

2) Two TotalDays after yesterday is:
2022-12-07 17:05:52.55733
Wednesday
  • Related