开发者

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

I need the get a date object that specifies the next 2:00am that will come.

So pretend the time is 14:00 on the 15th, I need the date object to contain 2:00 on开发者_如何学C the 16th If the time is 1:00 on the 16th, I need the date object to contain 2:00 on the 16th

How do I do this?


In C#

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

I'm sure there is a neater/cleverer way, but that will get the job done.


if the currenttime is before 2:00am, then the next 2:00am will be today else the next 2:00am will occur tomorrow (day + 1).

You will probably want to use a datetime object and increment the day by one, this should ensure that you are always on the correct date.


    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);
        }
    }


Whenever dealing with dates use the built in function because you will miss a case.

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


Add one day to today if it's after 02:00, otherwise add 0 days:

DateTime.Today.AddDays(DateTime.Now.Hour >= 2 ? 1 : 0)


I think any answer that includes adding hours to midnight or adding a timespan any larger than an hour is probably doomed to failure at some point due to daylight savings 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

For Mar 13,2011 at midnight the next 2:AM is Mar 14, at least in my time zone.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜