简体   繁体   中英

Javascript toLocaleTimeString() not working

Hello I have a piece of code

var date = new Date("11/12/2014 02:58:11 UTC");

console.info(date.toString());

console.info(date.toLocaleTimeString());

console.info(date.toLocaleDateString());

and display:

Tue Nov 11 2014 16:58:11 GMT-1000 (Hawaiian Standard Time)

9:58:11 AM

11/12/2014

My time zone is (UTC-10:00) Hawaii

date.toString(); displays correctly, but toLocaleTimeString() , toLocaleDateString() displays incorrect output

How do I fix this issue?

You can provide the time zone in the options parameter to toLocaleTimeString() :

date.toLocaleTimeString('en-US',{timeZone:'America/Adak'})

The time zone has to be specified from the IANA time zone database, which is a little odd... but it works.

Use it like so:

dateObj.toLocaleTimeString([locales[, options]])

console.log(date.toLocaleTimeString('en-US'));

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleTimeString

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM