[英]Convert UTC to standard date time format using javascript
如何使用Javascript將UTC時間轉換為正確的日期-時間格式?
這就是我想做的
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?
}
現在,如何從1388534400000獲得原始日期-2014-01-01?
****此外,請注意,當我這樣做時---新日期(1388534400000); 它給日期少了1天。 也就是說,它不會給出2014年1月1日 ,而是給出2013年12月31日 。 但是,我想要2014年1月1日。****
有什么方法與toUTC()方法相反嗎?
// _________對於toUTC()不起作用的用戶
“ toUTC”方法在我的Chrome控制台中有效。請參見下面的屏幕截圖
當您將包含連字符的字符串傳遞給Date
構造函數時,會將其視為UTC。 如果您不打發時間,它將被認為是午夜。 如果您位於UTC后面的時區(例如在大多數美洲),則將看到錯誤的當地時間轉換。
這是我的chrome開發者控制台的屏幕截圖,因此您可以了解我的意思
如果我改用斜杠:
考慮使用moment.js-它將接受格式參數,這將幫助您避免此問題。
嘗試使用以下內容:
new Date(new_d);
問題在於您實例化Date的方式。 Javascript將連字符解釋為utc日期,並將斜杠解釋為本地日期。
提供標記說明的結果。
var utcDate = new Date('2014-01-01') // returns a UTC date
var localDate = new Date('2014/01/01'); // Returns local date
但是要將日期轉換回起點字符串,您可以執行以下操作。
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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.