I'd like to convert a UTC date string into the current users timezone and maintain the format of the date string.
我想将UTC日期字符串转换为当前用户时区并保持日期字符串的格式。
For example, I have this code which works:
例如,我有这个代码有效:
var data = '2017-04-24 12:06:37';
var date = new Date(data+' UTC');
console.log(date.toString()); // logs "Mon Apr 24 2017 08:06:37 GMT-0400 (Eastern Daylight Time)"
How do I get this to output the new date string in the exact same format dynamically?
如何让它以动态完全相同的格式输出新的日期字符串?
2 个解决方案
#1
0
You have to add UTC
to the string before you convert it to a date.
在将字符串转换为日期之前,必须将UTC添加到字符串中。
To convert any date to a UTC string, you can use
要将任何日期转换为UTC字符串,您可以使用
var UTCstring = (new Date()).toUTCString();
See my snippet. It compares the five different methods.
看我的片段。它比较了五种不同的方法。
var date = new Date('2017-04-24 12:06:37 PM UTC');
var local = date.toString();
var utc = date.toUTCString();
var iso = date.toISOString();
var dateString = date.toDateString();
console.log(date);
console.log(local);
console.log(utc);
console.log(iso);
console.log(dateString);
#2
0
Solution I used with momentjs:
我用momentjs的解决方案:
moment.utc(value).local().format('YYYY-MM-DD HH:mm:ss');
#1
0
You have to add UTC
to the string before you convert it to a date.
在将字符串转换为日期之前,必须将UTC添加到字符串中。
To convert any date to a UTC string, you can use
要将任何日期转换为UTC字符串,您可以使用
var UTCstring = (new Date()).toUTCString();
See my snippet. It compares the five different methods.
看我的片段。它比较了五种不同的方法。
var date = new Date('2017-04-24 12:06:37 PM UTC');
var local = date.toString();
var utc = date.toUTCString();
var iso = date.toISOString();
var dateString = date.toDateString();
console.log(date);
console.log(local);
console.log(utc);
console.log(iso);
console.log(dateString);
#2
0
Solution I used with momentjs:
我用momentjs的解决方案:
moment.utc(value).local().format('YYYY-MM-DD HH:mm:ss');