How to set a time zone (or a Kind) of a DateTime value?

前端 未结 3 408
-上瘾入骨i
-上瘾入骨i 2020-12-29 18:15

I mean to store strict UTC time in a DateTime variable and output it in ISO 8601 format.

To do the last I\'ve used .ToString(\"yyyy-MM-ddTHH:mm:sszzz\"), and it has

相关标签:
3条回答
  • 2020-12-29 18:32

    You can try this as well, it is easy to implement

    TimeZone time2 = TimeZone.CurrentTimeZone;
    DateTime test = time2.ToUniversalTime(DateTime.Now);
    var singapore = TimeZoneInfo.FindSystemTimeZoneById("Singapore Standard Time");
    var singaporetime = TimeZoneInfo.ConvertTimeFromUtc(test, singapore);
    

    Change the text to which standard time you want to change.

    Use TimeZone feature of C# to implement.

    0 讨论(0)
  • 2020-12-29 18:47

    While the DateTime.Kind property does not have a setter, the static method DateTime.SpecifyKind creates a DateTime instance with a specified value for Kind.

    Altenatively there are several DateTime constructor overloads that take a DateTimeKind parameter

    0 讨论(0)
  • 2020-12-29 18:51

    If you want to get advantage of your local machine timezone you can use myDateTime.ToUniversalTime() to get the UTC time from your local time or myDateTime.ToLocalTime() to convert the UTC time to the local machine's time.

    // convert UTC time from the database to the machine's time
    DateTime databaseUtcTime = new DateTime(2011,6,5,10,15,00);
    var localTime = databaseUtcTime.ToLocalTime();
    
    // convert local time to UTC for database save
    var databaseUtcTime = localTime.ToUniversalTime();
    

    If you need to convert time from/to other timezones, you may use TimeZoneInfo.ConvertTime() or TimeZoneInfo.ConvertTimeFromUtc().

    // convert UTC time from the database to japanese time
    DateTime databaseUtcTime = new DateTime(2011,6,5,10,15,00);
    var japaneseTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Tokyo Standard Time");
    var japaneseTime = TimeZoneInfo.ConvertTimeFromUtc(databaseUtcTime, japaneseTimeZone);
    
    // convert japanese time to UTC for database save
    var databaseUtcTime = TimeZoneInfo.ConvertTimeToUtc(japaneseTime, japaneseTimeZone);
    

    List of available timezones

    TimeZoneInfo class on MSDN

    0 讨论(0)
提交回复
热议问题