从服务器我得到一个datetime变量的格式:6/29/2011 4:52:48 PM,它是UTC时间。我想使用JavaScript将其转换为当前用户的浏览器时区。
如何使用JavaScript或jQuery来做到这一点?
从服务器我得到一个datetime变量的格式:6/29/2011 4:52:48 PM,它是UTC时间。我想使用JavaScript将其转换为当前用户的浏览器时区。
如何使用JavaScript或jQuery来做到这一点?
当前回答
采用YYYY-MM-DD hh:mm:ss格式:
var date = new Date('2011-06-29T16:52:48+00:00');
date.toString() // "Wed Jun 29 2011 09:52:48 GMT-0700 (PDT)"
要从YYYY-MM-DD hh:mm:ss格式转换,请确保您的日期遵循ISO 8601格式。
Year:
YYYY (eg 1997)
Year and month:
YYYY-MM (eg 1997-07)
Complete date:
YYYY-MM-DD (eg 1997-07-16)
Complete date plus hours and minutes:
YYYY-MM-DDThh:mmTZD (eg 1997-07-16T19:20+01:00)
Complete date plus hours, minutes and seconds:
YYYY-MM-DDThh:mm:ssTZD (eg 1997-07-16T19:20:30+01:00)
Complete date plus hours, minutes, seconds and a decimal fraction of a second
YYYY-MM-DDThh:mm:ss.sTZD (eg 1997-07-16T19:20:30.45+01:00) where:
YYYY = four-digit year
MM = two-digit month (01=January, etc.)
DD = two-digit day of month (01 through 31)
hh = two digits of hour (00 through 23) (am/pm NOT allowed)
mm = two digits of minute (00 through 59)
ss = two digits of second (00 through 59)
s = one or more digits representing a decimal fraction of a second
TZD = time zone designator (Z or +hh:mm or -hh:mm)
需要注意的重要事项
你必须用T分隔日期和时间,空格在某些浏览器中不起作用 您必须使用这种格式+hh:mm设置时区,使用字符串作为时区(例如:'UTC')将在许多浏览器中不起作用。+hh:mm表示与UTC时区的偏移量。
其他回答
我有一个类似的问题,我使用以下代码代码(JavaScript)转换UTC到本地时间
let a = new Date() .toString a = a.getFullYear () () + "-" + ( a.getMonth () + 1) .toString()。padStart(2, "0") + "-" + a.getDate(). tostring()。padStart(“0”) console.log (a)
你应该得到(UTC)偏移量(分钟)的客户端:
var offset = new Date().getTimezoneOffset();
然后对从服务器得到的时间做相应的加减运算。
希望这能有所帮助。
在javascript中将字符串转换为日期之前,将'UTC'附加到字符串中:
var date = new Date('6/29/2011 4:52:48 PM UTC');
date.toString() // "Wed Jun 29 2011 09:52:48 GMT-0700 (PDT)"
这对我来说很管用
选项1:如果日期格式是"yyyy-mm-dd"或"yyyy-mm-dd H:n:s",例如:"2021-12-16 06:07:40"
使用这种格式,它不知道它是本地格式还是UTC时间。既然我们知道日期是UTC,我们必须确保JS知道它是UTC。所以我们必须将日期设置为UTC。
function setDateAsUTC(d) {
let date = new Date(d);
return new Date(
Date.UTC(
date.getFullYear(),
date.getMonth(),
date.getDate(),
date.getHours(),
date.getMinutes(),
date.getSeconds()
)
);
}
然后使用它
let d = "2021-12-16 06:07:40";
setDateAsUTC(d).toLocaleString();
// output: 12/16/2021, 6:07:40 AM
选项2:UTC日期格式为ISO-8601。大多数服务器的时间戳格式是ISO-8601 ex: '2011-06-29T16:52:48.000Z'。这样我们就可以把它传递给date函数和toLocaleString()函数。
let newDate = "2011-06-29T16:52:48.000Z"
new Date(newDate).toLocaleString();
//output: 6/29/2011, 4:52:48 PM
在Angular中,我这样使用Ben的回答:
$scope.convert = function (thedate) {
var tempstr = thedate.toString();
var newstr = tempstr.toString().replace(/GMT.*/g, "");
newstr = newstr + " UTC";
return new Date(newstr);
};
编辑:Angular 1.3.0添加了UTC日期过滤器,我还没有使用过,但它应该更简单,格式如下:
{{ date_expression | date : format : timezone}}
Angular 1.4.3 Date API