DateTime conversions using NodaTime on ASP.Net MVC

2019-06-06 17:42发布

I have the Date/Time stored in the database on the London's time zone (not UTC). What I need is to retrieve this Date/Time, convert it to UTC and display considering the user's time zone (which they define when registering to the site - ie: en-GB, en-US, etc).

My first question is more related to the MVC structure, as I'm totally new to this (am a WebForms developer) - Where should I put this conversion code/class/helper? Model? ViewModel?

The second question is the conversion itself - I've played around with the NodaTime test project but can't find a proper way to do this conversion.

Any help is much appreciated.

Thank you in advance.

2条回答
狗以群分
2楼-- · 2019-06-06 18:20

Jon Skeet may need to correct me, as I'm assuming this is correct in :

// Timezone data provider (inject with DI)
IDateTimeZoneProvider timeZoneProvider = DateTimeZoneProviders.Tzdb;

// London Timezone (can keep this as a singleton, since it'll be used often)
var londonTimeZone = timeZoneProvider["Europe/London"];

// Get your date/time from the database and map it as being local to London timezone
var yourDateFromDb = new DateTime(2013, 01, 23, 21, 00, 00); // This is what you'll get back from your database (although you may get back a DateTimeOffset)
ZoneLocalMapping zonedDbDateTime = londonTimeZone.AtLeniently(LocalDateTime.FromDateTime(yourDateFromDb)); <-- This is your date time with the correct offset (taking into account DST etc.)

// Map the London zoned date/time to the users local date/time
var usersTimezoneId = "Europe/Paris"; // <-- Store this value in users profile/db
var usersTimezone = timeZoneProvider[usersTimezoneId];
var usersZonedDateTime = zonedDbDateTime.WithZone(usersTimezone);

Assert.That(usersZonedDateTime.Hour == 22);

You should probably be aware that during timezone transitions (autumn clock change), you may get 2 possible dates for the zonedDbDateTime. The code here just gets the first or earliest date/time.

Edit: Updated code snippet with changes suggested by Jon Skeet

查看更多
别忘想泡老子
3楼-- · 2019-06-06 18:27

you can write some extension method like this :

public static DateTime ConvertToUtc(this DateTime d)
{
    //do conversin and return it
}

and you will be able to call it like @Model.MyDate.ConvertToUtc() from any view you wish as long as you have the namespace of the ConvertToUtc inclucded on the top of page. and to do the conversion see this pages

Convert DateTime from UTC to a user provided time zone with C#

http://www.dotnetcurry.com/ShowArticle.aspx?ID=593

How to work with time zones in ASP.NET?

查看更多
登录 后发表回答