DateTime conversions using NodaTime on ASP.Net MVC 3 Razor website. How to?

不问归期 提交于 2019-12-08 06:52:43

问题


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.


回答1:


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

// 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




回答2:


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?



来源:https://stackoverflow.com/questions/16164994/datetime-conversions-using-nodatime-on-asp-net-mvc-3-razor-website-how-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!