开发者

How to get all records for the entire day?

I have some records and I only want to show that day so if it is July 6th it should be

7/6/2011 12:00:00 AM to 7/6/2011 11:59:59 AM

Say I have a record that has a due date of July 6th 7pm (my local time)

07:00:00 p.m. Wednesday July 6, 2011 in Canada/Pacific converts to
02:00:00 a.m. Thursday July 7, 2011 in UTC

That is 2am UTC time. This is stored in the database(I store only UTC dates and then use UTC to grab records I need then convert to local time zone)

Now I开发者_如何转开发 have this code

    DateTime startDate = DateTime.UtcNow.Date;


    DateTime endDate = DateTime.UtcNow.Date.AddSeconds(86399);

    return new DateFilterRange(startDate, endDate);

// result
7/6/2011 12:00:00 AM to 7/6/2011 11:59:59 AM

Of course this does not grab the above task because in the db the record is stored as July 7th but the user is still in July 6th.

I am thinking I have to use the offset some how but I am not how to use it.


It sounds like you need to take your local time boundaries, e.g. the start of the local day, convert those to UTC, and then filter by that.

Note that your initial example only shows the first half of July 6th - 12am to 12pm. It's not clear whether that's what you want.

Be aware that in some time zones, not all days start at midnight - if a DST change occurs when midnight would occur, the day may actually start at 1am.

EDIT: Just to be clear...

You need to get year, month and day from the user somehow. If that's specified in the UI, you can use this code:

DateTime localDate = new DateTime(year, month, day, 0, 0, 0,
                                  DateTimeKind.Unspecified);

Otherwise, you'll want something like:

// Work out the current date in the *user's* time zone
DateTime localDate = TimeZoneInfo.ConvertTime(DateTime.UtcNow, timeZone).Date;

// And then convert that "start of day" back to UTC
DateTime utcStart = TimeZoneInfo.ConvertTimeToUtc(localDate, timeZone);
DateTime utcEnd = TimeZoneInfo.ConvertTimeToUtc(localDate.AddDays(1),
                                                timeZone);

Note that this doesn't take into account time zones where midnight doesn't always happen.


Note: I'm assuming you already know the users time zone, based on comments...

1 get "right now". 2 convert to user's time zone. 3 get day boundaries in user's time zone. 4 convert boundaries to UTC time.

DateTime userDayStart = TimeZoneInfo.ConvertTimeFromUtc(
    DateTime.UtcNow,
    usersTimeZone
).Date;

DateTime utcStart = TimeZoneInfo.ConvertTimeToUtc(
    userDayStart,
    usersTimeZone
);

DateTime utcEnd = TimeZoneInfo.ConvertTimeToUtc(
    userDayStart.AddDays(1),
    usersTimeZone
);

Of course, the .Date and .AddDays() operations happen in the local time zone, so it won't be perfect with regard to daylight savings time etc.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜