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

若如初见. 提交于 2019-12-07 03:58:28

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

ePezhman

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?

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