Correct way to convert datetime timezone to display

We are developing a website, and currently the time zone of the website and database is in the German time zone (European standard time zone). But the application is also available from the USA. The application has a screen containing a DateTime field named ValidFrom , and the time we save is UTC . Currently, users do not select a time, so we use the built-in DateTime.UTCNow .NET to store the DateTime value in the database. But the problem is during the show, we need to display it in accordance with the user's time zone. Therefore, after searching for many hours, we found two solutions that use the moment , and another approach uses DateTime.SpecifyKind. We tried using moment.js , but it again changed the time of the date to local time. So we ended up using DateTime.SpecifyKind , as shown below.

[DataMember]
private DateTime _validFrom;
public DateTime ValidFrom
{
    get { return _validFrom; }
    set { _validFrom = DateTime.SpecifyKind(value, DateTimeKind.Utc); }
} 

And now the values ​​are displayed in accordance with the time zone. But I doubt if it is suitable for handling timezone display or any other better solution?

+4
source share
2 answers

I would use DateTimeOffsetsomething like:

var utc = DateTimeOffset.UtcNow;
var tz = TimeZoneInfo.FindSystemTimeZoneById("Your Specific Time Zone Id");
var zonedDateTime = TimeZoneInfo.ConvertTime(utc, tz);

UTC UTC , . NodaTime, - . DateTime .Net .

+3

:

public static DateTime ConvertFromUTC(this DateTime date, TimeZoneInfo destZone)
{
    var utcZone = TimeZoneInfo.FindSystemTimeZoneById("UTC");
    return TimeZoneInfo.ConvertTime(date, utcZone, destZone);
}

, - , . , DST . , , -, : ?

+1

Source: https://habr.com/ru/post/1687314/


All Articles