Does Javascript date toLocaleString account for DST?

后端 未结 3 820
礼貌的吻别
礼貌的吻别 2021-01-24 00:46

I have set a deadline in UTC, as shown below, and I\'m wondering what exactly the toLocaleString() method will do to it on user\'s local machines. For instance, will it account

相关标签:
3条回答
  • 2021-01-24 01:07

    We don't know what exactly the toLocaleString method does (§15.9.5.5):

    This function returns a String value. The contents of the String are implementation-dependent, but are intended to represent the Date in the current time zone in a convenient, human-readable form that corresponds to the conventions of the host environment’s current locale.

    But yes, most implementations will consider DST if it is active in the current local timezone. For your example I'm getting "Mittwoch, 1. Mai 2013 18:15:00" - CEST.

    Will I need to insert additional code that checks where the user is, and then fixes the displayed time?

    I think you can trust toLocaleString - the browser should respect the user's settings. If you want to do it manually, check out timezone.js.

    0 讨论(0)
  • 2021-01-24 01:07

    In general, the answer is yes. JavaScript will represent the UTC value at the appropriate local time based on the time zone settings of the computer it is running on. This includes adjustment for DST. However, as others have pointed out, the details are implementation specific.

    If you want a consistent output, I would use a library to format your dates instead of relying on the default implementation. The best library (IMHO) for this is moment.js. The live examples on their main page will give you an idea of what it can do.

    UPDATE

    If you are passing UTC values that you want converted to the correct local time, and that time falls into a period where the time zone rules are different than the current one - then the results will be invalid. This is crazy, but true - and by design in the ECMA spec. Read - JavaScript Time Zone is wrong for past Daylight Saving Time transition rules

    0 讨论(0)
  • 2021-01-24 01:16

    As you use "UTC" the date itself will be UTC format, but the toLocaleString() takes client's locale into account, which means it'll return the date in string updated with all and every changes typical to client's regional and locale settings (DST, date/time format, etc).
    As JS documentation describes this: "The toLocaleString() method converts a Date object to a string, using locale settings.".
    If you want to avoid this, use the toUTCString() method instead.

    I'd also recommend reading the accepted solution for the question Javascript dates: what is the best way to deal with Daylight Savings Time? to avoid (at least, to try to avoid :) future issues related to JS, browsers and locales.

    Hope this helps!

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