我希望服务器在HTML中始终以UTC时间提供日期,在客户端使用JavaScript将其转换为用户本地时区。
如果能够输出用户所在地区的日期格式,则更佳。
似乎以UTC日期开始最保险的方法是创建一个新的Date
对象,并使用setUTC…
方法将其设置为所需的日期/时间。
然后各种toLocale…String
方法将提供本地化输出。
// This would come from the server.
// Also, this whole block could probably be made into an mktime function.
// All very bare here for quick grasping.
d = new Date();
d.setUTCFullYear(2004);
d.setUTCMonth(1);
d.setUTCDate(29);
d.setUTCHours(2);
d.setUTCMinutes(45);
d.setUTCSeconds(26);
console.log(d); // -> Sat Feb 28 2004 23:45:26 GMT-0300 (BRT)
console.log(d.toLocaleString()); // -> Sat Feb 28 23:45:26 2004
console.log(d.toLocaleDateString()); // -> 02/28/2004
console.log(d.toLocaleTimeString()); // -> 23:45:26
最好从UTC parse日期字符串,如下所示(在服务器上创建一个ISO-8601兼容字符串以在所有浏览器中获得一致的结果):
var m = moment("2013-02-08T09:30:26Z");
m
,moment.js默认使用本地时区进行显示操作。有许多方法可以格式化日期和时间值或提取其中的部分。m.format('LLL') // Returns "February 8 2013 8:30 AM" on en-us
对于旧项目,只需使用jQuery
。 - XenostoLocaleString
之外,有什么解决方案吗? - user924在JS中,没有简单和跨平台的方法来格式化本地日期时间,除非将每个属性转换为上述提到的方式。
这是我用来获取本地YYYY-MM-DD的快速hack。请注意,这是一个hack,因为最终日期将不再具有正确的时区(所以您必须忽略时区)。如果我需要更多其他内容,我会使用moment.js。
var d = new Date();
d = new Date(d.getTime() - d.getTimezoneOffset() * 60000)
var yyyymmdd = t.toISOString().slice(0, 10);
// 2017-05-09T08:24:26.581Z (but this is not UTC)
d.getTimezoneOffset()返回的是相对于UTC时间的时区偏移量,单位为分钟,而d.getTime()返回的是毫秒数,因此需要乘以60,000。
2021年,您可以使用浏览器原生的Intl.DateTimeFormat
const utcDate = new Date(Date.UTC(2020, 11, 20, 3, 23, 16, 738));
console.log(new Intl.DateTimeFormat().format(utcDate));
// expected output: "21/04/2021", my locale is Switzerland
以下是直接从文档中获取的内容:
const date = new Date(Date.UTC(2020, 11, 20, 3, 23, 16, 738));
// Results below assume UTC timezone - your results may vary
// Specify default date formatting for language (locale)
console.log(new Intl.DateTimeFormat('en-US').format(date));
// expected output: "12/20/2020"
// Specify default date formatting for language with a fallback language (in this case Indonesian)
console.log(new Intl.DateTimeFormat(['ban', 'id']).format(date));
// expected output: "20/12/2020"
// Specify date and time format using "style" options (i.e. full, long, medium, short)
console.log(new Intl.DateTimeFormat('en-GB', { dateStyle: 'full', timeStyle: 'long' }).format(date));
// Expected output "Sunday, 20 December 2020 at 14:23:16 GMT+11"
一旦你构建好日期对象,这里有一个转换的片段:
该函数接受一个UTC格式的日期对象和格式字符串。
您需要一个Date.strftime
原型。
function UTCToLocalTimeString(d, format) {
if (timeOffsetInHours == null) {
timeOffsetInHours = (new Date().getTimezoneOffset()/60) * (-1);
}
d.setHours(d.getHours() + timeOffsetInHours);
return d.strftime(format);
}
getTimezoneOffset()/60
可能会返回一个小数(例如印度时区偏移量为 +05:30,将返回 5.5)。小数部分将被截断。否则,设置小时数确实会更新其他值(将小时数设置为 48 并查看发生了什么)。 - RobG// new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]])
var serverDate = new Date(2018, 5, 30, 19, 13, 15); // just any date that comes from server
var serverDateStr = serverDate.toLocaleString("en-US", {
year: 'numeric',
month: 'numeric',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric'
})
var userDate = new Date(serverDateStr + " UTC");
var locale = window.navigator.userLanguage || window.navigator.language;
var clientDateStr = userDate.toLocaleString(locale, {
year: 'numeric',
month: 'numeric',
day: 'numeric'
});
var clientDateTimeStr = userDate.toLocaleString(locale, {
year: 'numeric',
month: 'numeric',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric'
});
console.log("Server UTC date: " + serverDateStr);
console.log("User's local date: " + clientDateStr);
console.log("User's local date&time: " + clientDateTimeStr);
以下是我在过去项目中使用过的内容:
var myDate = new Date();
var tzo = (myDate.getTimezoneOffset()/60)*(-1);
//get server date value here, the parseInvariant is from MS Ajax, you would need to do something similar on your own
myDate = new Date.parseInvariant('<%=DataCurrentDate%>', 'yyyyMMdd hh:mm:ss');
myDate.setHours(myDate.getHours() + tzo);
//here you would have to get a handle to your span / div to set. again, I'm using MS Ajax's $get
var dateSpn = $get('dataDate');
dateSpn.innerHTML = myDate.localeFormat('F');
getTimezoneOffset()/60
经常会返回一个小数值。这在 1900 年之前的日期尤其如此,许多地方的偏移量以分钟和秒为单位。此外,JavaScript 日期现在需要支持历史偏移量。例如,在 1890 年,莫斯科的偏移量为 +2:30:17。请参见 浏览器、时区、Chrome 67 错误。 - RobGfunction getLocalDate(php_date) {
var dt = new Date(php_date);
var minutes = dt.getTimezoneOffset();
dt = new Date(dt.getTime() + minutes*60000);
return dt;
}
var localdateObj = getLocalDate('2015-09-25T02:57:46');
language = request.META.get('HTTP_ACCEPT_LANGUAGE')
return render(request, 'cssexy/index.html', { "language": language })
HTML:将其写入隐藏输入框中:
<input type="hidden" id="browserlanguage" value={{ language }}/>
JavaScript: 获取隐藏输入框的值,例如en-GB,en-US;q=0.8,en;q=0.6/,然后通过替换和正则表达式仅获取列表中的第一种语言
const browserlanguage = document.getElementById("browserlanguage").value;
var defaultlang = browserlanguage.replace(/(\w{2}\-\w{2}),.*/, "$1");
var options = { hour: "2-digit", minute: "2-digit" };
var dt = (new Date(str)).toLocaleDateString(defaultlang, options);
var d = new Date(Date.UTC(2004,1,29,2,45,26));
- m1kaeltoLocaleString()
函数中不考虑用户的语言环境。 - bennonew Date(Date.UTC(year,month,...))
,这样也要少打很多字。 - RobG