[英]Convert UTC to standard date time format using javascript
How can I convert a UTC time into proper date - time format using Javascript? 如何使用Javascript将UTC时间转换为正确的日期-时间格式?
This is what I want to do 这就是我想做的
var d = new Date("2014-01-01");
var new_d = d.toUTC(); // 1388534400000
var old_d = function(new_d){
// return "2014-01-01" // how can i get this?
}
Now How, can i get orignal date - 2014-01-01 from 1388534400000? 现在,如何从1388534400000获得原始日期-2014-01-01?
****Also, Please note that when i do this --- new Date(1388534400000); ****此外,请注意,当我这样做时---新日期(1388534400000); it gives date 1 day less. 它给日期少了1天。 That is, instead of giving Jan 01 2014 , it gives Dec 31 2013 . 也就是说,它不会给出2014年1月1日 ,而是给出2013年12月31日 。 But, I want Jan 01 2014.**** 但是,我想要2014年1月1日。****
Is there any method to do the opposite of toUTC() method? 有什么方法与toUTC()方法相反吗?
// _________ For those whose toUTC() doesnt work // _________对于toUTC()不起作用的用户
"toUTC" method works in console of my chrome See screen shot below “ toUTC”方法在我的Chrome控制台中有效。请参见下面的屏幕截图
When you pass a string containing hyphens to the Date
constructor, it will treat that as UTC. 当您将包含连字符的字符串传递给Date
构造函数时,会将其视为UTC。 And if you don't pass a time, it will consider it to be midnight. 如果您不打发时间,它将被认为是午夜。 If you are in a time zone that is behind UTC (such as in most of the Americas), you will see the wrong local time conversion. 如果您位于UTC后面的时区(例如在大多数美洲),则将看到错误的当地时间转换。
Here's a screenshot of my chrome dev console, so you can see what I mean 这是我的chrome开发者控制台的屏幕截图,因此您可以了解我的意思
If I pass slashes instead: 如果我改用斜杠:
Consider using moment.js - which will accept a format parameter that will help you avoid this issue. 考虑使用moment.js-它将接受格式参数,这将帮助您避免此问题。
尝试使用以下内容:
new Date(new_d);
The problem lies with the way you instantiate the Date . 问题在于您实例化Date的方式。 Javascript interpretes the hyphens as an utc date, and slashes as local dates. Javascript将连字符解释为utc日期,并将斜杠解释为本地日期。
Giving the results that mark Explains. 提供标记说明的结果。
var utcDate = new Date('2014-01-01') // returns a UTC date
var localDate = new Date('2014/01/01'); // Returns local date
But to translate a date back to your starting point string, you can do the following. 但是要将日期转换回起点字符串,您可以执行以下操作。
function toDateString(utcMillis){
var date = new Date(utcMillis);
d = date.getDate();
m = date.getMonth() +1;
y = date.getFullYear();
return y + '-' + addLeadingZero(m, 2) + '-' + addLeadingZero(d,2);
}
function addLeadingZero(n, length){
n = n+'';
if(n.length<length)
return addLeadingZero('0'+n, length--);
else
return n;
}
function toUTCDateString(utcMillis){
var date = new Date(utcMillis);
d = date.getUTCDate();
m = date.getUTCMonth() +1;
y = date.getUTCFullYear();
return y + '-' + addLeadingZero(m, 2) + '-' + addLeadingZero(d,2);
}
To play around with it, and see it for yourself, see this Fiddle: 要尝试使用它,并亲自欣赏它,请参阅此提琴:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.