How to find the exact date of the next 2:00 a.m. in .net

I need to get a date object that defines the next 2:00 in the morning that will come.

So, pretend that the time is 15.00, I need a date object that should contain 2:00 on the 16th. If the time is 16:00, I need the date object to contain 2:00 on the 16th

How to do it?

+3
source share
7 answers

In c #

DateTime dt = DateTime.Today.AddHours(2);
if (dt < DateTime.Now)
    dt = dt.AddDays(1);

I'm sure there is a tidier / smarter way, but this will do the job.

+10
source

if the current time precedes 2:00 in the morning, then the next 2:00 in the morning will be different today at the next 2:00 in the morning tomorrow (day + 1).

, datetime , , .

+1
    private DateTime GetTwoAm()
    {
        DateTime time1 = DateTime.Now;
        DateTime time2 = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 2, 0, 0);

        if (time1 <= time2)
        {
            return time2;
        }
        else
        {
            return time2.AddDays(1);
        }
    }
+1

Whenever it comes to dates, use the built-in function because you miss the case.

DateTime today2am = DateTime.Now.Date.AddHours(2);
DateTime Nexttwoam = (DateTime.Now < today2am) ? (today2am) : today2am.AddDays(1);
+1
source

Add one day for today, if it is after 02:00, otherwise add 0 days:

DateTime.Today.AddDays(DateTime.Now.Hour >= 2 ? 1 : 0)
+1
source
DateTime dt = DateTime.Now;
if (dt.Hour >= 2)
    dt = dt.Date.Add(new TimeSpan(1, 2, 0, 0));
else
    dt = dt.Date.Add(new TimeSpan(2, 0, 0));
0
source

I think that any answer, including adding hours at midnight or adding time in excess of an hour, is probably doomed to fail at some point due to daylight saving time.

    Dim dtToCheck As DateTime = "3/13/2011 00:12"

    Dim tz As TimeZone = System.TimeZone.CurrentTimeZone

    Dim dl As System.Globalization.DaylightTime = tz.GetDaylightChanges(dtToCheck.Year)



    Dim dt As DateTime = Format(dtToCheck, "yyyy-MM-dd HH:00:00.000")

    If dt < dtToCheck Then dt = dt.AddHours(1)

    Do Until dt.Hour = 2
        If dt < dl.Start And dt.AddHours(1) >= dl.Start Then
            'will go over 
            dt = dt.Add(dl.Delta) 
        End If
        dt = dt.AddHours(1)
    Loop

    TextBox2.Text = dt

On March 13,2011 at midnight the following 2: AM - March 14th, at least in my time zone.

0
source

Source: https://habr.com/ru/post/1785446/


All Articles