以用户的语言环境格式和时间偏移显示日期/时间

kch*_*kch 157 javascript timezone datetime

我希望服务器始终在HTML中提供UTC日期,并在客户端站点上使用JavaScript将其转换为用户的本地时区.

如果我可以用户的区域设置日期格式输出,则可以获得奖励.

kch*_*kch 158

似乎从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
Run Code Online (Sandbox Code Playgroud)

一些参考:

  • 对不起,但这种方法不起作用(我在澳大利亚),当我运行上面的代码时,日期以美国格式显示.此外,[MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString)说'使用的语言环境和返回的字符串形式完全依赖于实现' . (8认同)
  • 上述初始化的单行版本:`var d = new Date(Date.UTC(2004,1,29,2,45,26));` (6认同)
  • 值得考虑的是Chrome(截至v35)没有考虑用户在`toLocaleString()函数中的语言环境. (4认同)
  • 创建新日期,然后单独设置各个部分可能会导致错误。例如,创建 1 月 31 日的日期,然后将月份设置为 2 月,会将日期更改为 3 月。它应该一次性完成:`new Date(Date.UTC(year,month, ...))`,这也减少了很多输入。 (2认同)

the*_*Dmi 65

对于新项目,只需使用moment.js

这个问题已经过时了,所以当时并不存在moment.js,但对于新项目,它简化了很多这样的任务.

最好从UTC 解析日期字符串,如下所示(在服务器上创建一个ISO-8601兼容字符串,以便在所有浏览器中获得一致的结果):

var m = moment("2013-02-08T09:30:26Z");
Run Code Online (Sandbox Code Playgroud)

现在只需m在您的应用程序中使用,moment.js默认为本地时区进行显示操作.有许多方法可以格式化日期和时间值或提取部分.

您甚至可以在用户区域设置中格式化一个时刻对象,如下所示:

m.format('LLL') // Returns "February 8 2013 8:30 AM" on en-us
Run Code Online (Sandbox Code Playgroud)

要将moment.js对象转换为不同的时区(即既不是本地时区也不是UTC),您将需要moment.js时区扩展.该页面还有一些示例,使用起来非常简单.


jop*_*jop 20

您可以使用new Date().getTimezoneOffset()/60时区.还有toLocaleString()一种使用用户的语言环境显示日期的方法.

以下是整个列表:使用日期


Fla*_*ken 13

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
Run Code Online (Sandbox Code Playgroud)

以下是直接来自文档的内容:

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"
Run Code Online (Sandbox Code Playgroud)


sim*_*rmy 7

一旦构建了日期对象,这里就是转换的片段:

该函数采用UTC格式的Date对象和格式字符串.
你需要一个Date.strftime原型.

function UTCToLocalTimeString(d, format) {
    if (timeOffsetInHours == null) {
        timeOffsetInHours = (new Date().getTimezoneOffset()/60) * (-1);
    }
    d.setHours(d.getHours() + timeOffsetInHours);

    return d.strftime(format);
}
Run Code Online (Sandbox Code Playgroud)

  • 你是从哪里开始的? (6认同)
  • @ChristoKiwi——传递给 *setHours* 的值预计是一个整数 `getTimezoneOffset()/60` 可能会返回一个分数(例如,印度偏移量 +05:30 将返回 5.5)。小数被截断。否则,设置小时数会更新其他值(将小时数设置为 48,看看会发生什么)。 (2认同)

Ser*_*gey 7

// 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);
Run Code Online (Sandbox Code Playgroud)


Jer*_*one 6

在JS中,除了如上所述转换每个属性之外,没有简单且跨平台的方法来格式化本地日期时间。

这是我用来获取本地YYYY-MM-DD的快速技巧。请注意,这是一个hack,因为最终日期将不再具有正确的时区(因此您必须忽略时区)。如果我还有其他需要,可以使用moment.js。

var d = new Date();    
d = new Date(d.getTime() - d.getTimezoneOffset() * 60000)
var yyyymmdd = t.toISOString().slice(0,0); 
// 2017-05-09T08:24:26.581Z (but this is not UTC)
Run Code Online (Sandbox Code Playgroud)

d.getTimezoneOffset()返回以分钟为单位的时区偏移量,而d.getTime()以毫秒为单位,因此为x 60,000。


小智 5

这是我在过去的项目中使用的内容:

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');
Run Code Online (Sandbox Code Playgroud)

  • 这是特定于ASP.NET的东西. (4认同)