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

时间:2022-09-18 07:28:47

I want the server to always serve dates in UTC in the HTML, and have JavaScript on the client site convert it to the user's local timezone.

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

Bonus if I can output in the user's locale date format.

如果我能以用户的语言环境日期格式输出,那就更好了。

13 个解决方案

#1


134  

Seems the most foolproof way to start with a UTC date is to create a new Date object and use the setUTC… methods to set it to the date/time you want.

似乎从UTC日期开始最简单的方法是创建一个新的日期对象,并使用setUTC…方法将其设置为所需的日期/时间。

Then the various toLocale…String methods will provide localized output.

然后,各种toLocale…String方法将提供本地化输出。

Example:

// 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

Some references:

#2


55  

For new projects, just use moment.js

This question is pretty old, so moment.js didn't exist at that time, but for new projects, it simplifies tasks like this a lot.

这个问题由来已久。当时js并不存在,但对于新项目来说,它大大简化了类似这样的任务。

It's best to parse your date string from UTC as follows (create an ISO-8601 compatible string on the server to get consistent results across all browsers):

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

var m = moment("2013-02-08T09:30:26Z");

Now just use m in your application, moment.js defaults to the local timezone for display operations. There are many ways to format the date and time values or extract portions of it.

现在在你的应用中使用m。js默认使用本地时区进行显示操作。有许多方法可以格式化日期和时间值或提取其中的一部分。

You can even format a moment object in the users locale like this:

您甚至可以在用户语言环境中格式化moment对象,如下所示:

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

To transform a moment.js object into a different timezone (i.e. neither the local one nor UTC), you'll need the moment.js timezone extension. That page has also some examples, it's pretty simple to use.

转换。将js对象放到不同的时区(即既不是本地时区,也不是UTC),您需要这个时刻。js时区扩展。这个页面也有一些例子,使用起来很简单。

#3


19  

You can use new Date().getTimezoneOffset()/60 for the timezone. There is also a toLocaleString() method for displaying a date using the user's locale.

您可以为时区使用new Date(). gettimezoneoffset()/60。还有一个toLocaleString()方法,用于使用用户的语言环境显示日期。

Here's the whole list: Working with Dates

这是完整的列表:处理日期

#4


5  

Here's what I've used in past projects:

以下是我在过去的项目中使用过的:

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');

#5


5  

Once you have your date object constructed, here's a snippet for the conversion:

一旦构造了date对象,下面是转换的代码片段:

The function takes a UTC formatted Date object and format string.
You will need a Date.strftime prototype.

函数接受UTC格式的日期对象和格式字符串。你需要一个约会。strftime原型。

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

    return d.strftime(format);
}

#6


3  

The .getTimezoneOffset() method reports the time-zone offset in minutes, counting "westwards" from the GMT/UTC timezone, resulting in an offset value that is negative to what one is commonly accustomed to. (Example, New York time would be reported to be +240 minutes or +4 hours)

gettimezoneoffset()方法以分钟为单位报告时区偏移量,从GMT/UTC时区计数“向西”,从而得到一个与通常习惯的偏移量为负的偏移值。(例如,纽约时间为+240分钟或+4小时)

To the get a normal time-zone offset in hours, you need to use:

要获得以小时为单位的正常时区偏移,您需要使用:

var timeOffsetInHours = -(new Date()).getTimezoneOffset()/60

Important detail:
Note that daylight savings time is factored into the result - so what this method gives you is really the time offset - not the actual geographic time-zone offset.

重要的细节:请注意,日光节约时间被考虑到结果中——因此这个方法提供的实际上是时间偏移量——而不是实际的地理时区偏移量。

#7


3  

With date from PHP code I used something like this..

使用PHP代码的日期,我使用了如下内容。

function getLocalDate(php_date) {
  var dt = new Date(php_date);
  var minutes = dt.getTimezoneOffset();
  dt = new Date(dt.getTime() + minutes*60000);
  return dt;
}

We can call it like this

我们可以这样称呼它

var localdateObj = getLocalDate('2015-09-25T02:57:46');

#8


3  

I mix the answers so far and add to it, because I had to read all of them and investigate additionally for a while to display a date time string from db in a user's local timezone format.

我将到目前为止的答案混合在一起,并添加到其中,因为我必须阅读所有答案,并对它们进行额外的研究,以便以用户的本地时区格式显示来自db的日期时间字符串。

The datetime string comes from a python/django db in the format: 2016-12-05T15:12:24.215Z

datetime字符串来自于python/django db格式:2016-12-05T15:12:24.215Z。

Reliable detection of the browser language in JavaScript doesn't seem to work in all browsers (see JavaScript for detecting browser language preference), so I get the browser language from the server.

对JavaScript中浏览器语言的可靠检测似乎并不适用于所有浏览器(请参阅JavaScript以检测浏览器语言偏好),因此我从服务器获得浏览器语言。

Python/Django: send request browser language as context parameter:

Python/Django:将请求浏览器语言作为上下文参数发送:

language = request.META.get('HTTP_ACCEPT_LANGUAGE')
return render(request, 'cssexy/index.html', { "language": language })

HTML: write it in a hidden input:

HTML:写在一个隐藏的输入:

<input type="hidden" id="browserlanguage" value={{ language }}/>

JavaScript: get value of hidden input e.g. en-GB,en-US;q=0.8,en;q=0.6/ and then take the first language in the list only via replace and regular expression

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");

JavaScript: convert to datetime and format it:

JavaScript:转换到datetime并格式化它:

var options = { hour: "2-digit", minute: "2-digit" };
var dt = (new Date(str)).toLocaleDateString(defaultlang, options);

See: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString

参见:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString

The result is (browser language is en-gb): 05/12/2016, 14:58

结果是(浏览器语言为en-gb): 05/12/2016, 14:58

#9


2  

The best solution I've come across is to create [time display="llll" datetime="UTC TIME" /] Tags, and use javascript (jquery) to parse and display it relative to the user's time.

我遇到的最好的解决方案是创建[time display="llll" datetime="UTC time " /]标签,并使用javascript (jquery)来解析和显示它相对于用户的时间。

http://momentjs.com/ Moment.js

http://momentjs.com/ Moment.js

will display the time nicely.

会很好地显示时间。

#10


2  

You could use the following, which reports the timezone offset from GMT in minutes:

您可以使用下面的方法,它报告了时区从格林尼治时间到分钟的偏移量:

new Date().getTimezoneOffset();

Note : - this function return a negative number.

注意:-这个函数返回一个负数。

#11


1  

getTimeZoneOffset() and toLocaleString are good for basic date work, but if you need real timezone support, look at mde's TimeZone.js.

getTimeZoneOffset()和toLocaleString非常适合基本的日期工作,但是如果您需要真正的时区支持,请查看mde的timezone .js。

There's a few more options discussed in the answer to this question

在这个问题的答案中,我们还讨论了一些选项

#12


1  

In JS there are no simple and cross platform ways to format local date time, outside of converting each property as mentioned above.

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

Here is a quick hack I use to get the local YYYY-MM-DD. Note that this is a hack, as the final date will not have the correct timezone anymore (so you have to ignore timezone). If I need anything else more, I use moment.js.

这里有一个我用来获取本地yyyyy - mm - dd的快速技巧。注意,这是一个技巧,因为最终的日期将不再具有正确的时区(因此必须忽略时区)。如果我还需要什么,我就用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)

The d.getTimezoneOffset() returns the time zone offset in minutes, and the d.getTime() is in ms, hence the x 60,000.

d.getTimezoneOffset()返回时间区域以分钟为单位的偏移量,而d.getTime()是在ms中,因此是x 60000。

#13


-8  

Don't know how to do locale, but javascript is a client side technology.

不知道如何进行语言环境,但是javascript是客户端技术。

usersLocalTime = new Date();

will have the client's time and date in it (as reported by their browser, and by extension the computer they are sitting at). It should be trivial to include the server's time in the response and do some simple math to guess-timate offset.

将客户的时间和日期包含在其中(由他们的浏览器报告,并扩展到他们所在的计算机)。在响应中包含服务器的时间,并做一些简单的计算来猜测估计值,这应该是微不足道的。

#1


134  

Seems the most foolproof way to start with a UTC date is to create a new Date object and use the setUTC… methods to set it to the date/time you want.

似乎从UTC日期开始最简单的方法是创建一个新的日期对象,并使用setUTC…方法将其设置为所需的日期/时间。

Then the various toLocale…String methods will provide localized output.

然后,各种toLocale…String方法将提供本地化输出。

Example:

// 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

Some references:

#2


55  

For new projects, just use moment.js

This question is pretty old, so moment.js didn't exist at that time, but for new projects, it simplifies tasks like this a lot.

这个问题由来已久。当时js并不存在,但对于新项目来说,它大大简化了类似这样的任务。

It's best to parse your date string from UTC as follows (create an ISO-8601 compatible string on the server to get consistent results across all browsers):

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

var m = moment("2013-02-08T09:30:26Z");

Now just use m in your application, moment.js defaults to the local timezone for display operations. There are many ways to format the date and time values or extract portions of it.

现在在你的应用中使用m。js默认使用本地时区进行显示操作。有许多方法可以格式化日期和时间值或提取其中的一部分。

You can even format a moment object in the users locale like this:

您甚至可以在用户语言环境中格式化moment对象,如下所示:

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

To transform a moment.js object into a different timezone (i.e. neither the local one nor UTC), you'll need the moment.js timezone extension. That page has also some examples, it's pretty simple to use.

转换。将js对象放到不同的时区(即既不是本地时区,也不是UTC),您需要这个时刻。js时区扩展。这个页面也有一些例子,使用起来很简单。

#3


19  

You can use new Date().getTimezoneOffset()/60 for the timezone. There is also a toLocaleString() method for displaying a date using the user's locale.

您可以为时区使用new Date(). gettimezoneoffset()/60。还有一个toLocaleString()方法,用于使用用户的语言环境显示日期。

Here's the whole list: Working with Dates

这是完整的列表:处理日期

#4


5  

Here's what I've used in past projects:

以下是我在过去的项目中使用过的:

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');

#5


5  

Once you have your date object constructed, here's a snippet for the conversion:

一旦构造了date对象,下面是转换的代码片段:

The function takes a UTC formatted Date object and format string.
You will need a Date.strftime prototype.

函数接受UTC格式的日期对象和格式字符串。你需要一个约会。strftime原型。

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

    return d.strftime(format);
}

#6


3  

The .getTimezoneOffset() method reports the time-zone offset in minutes, counting "westwards" from the GMT/UTC timezone, resulting in an offset value that is negative to what one is commonly accustomed to. (Example, New York time would be reported to be +240 minutes or +4 hours)

gettimezoneoffset()方法以分钟为单位报告时区偏移量,从GMT/UTC时区计数“向西”,从而得到一个与通常习惯的偏移量为负的偏移值。(例如,纽约时间为+240分钟或+4小时)

To the get a normal time-zone offset in hours, you need to use:

要获得以小时为单位的正常时区偏移,您需要使用:

var timeOffsetInHours = -(new Date()).getTimezoneOffset()/60

Important detail:
Note that daylight savings time is factored into the result - so what this method gives you is really the time offset - not the actual geographic time-zone offset.

重要的细节:请注意,日光节约时间被考虑到结果中——因此这个方法提供的实际上是时间偏移量——而不是实际的地理时区偏移量。

#7


3  

With date from PHP code I used something like this..

使用PHP代码的日期,我使用了如下内容。

function getLocalDate(php_date) {
  var dt = new Date(php_date);
  var minutes = dt.getTimezoneOffset();
  dt = new Date(dt.getTime() + minutes*60000);
  return dt;
}

We can call it like this

我们可以这样称呼它

var localdateObj = getLocalDate('2015-09-25T02:57:46');

#8


3  

I mix the answers so far and add to it, because I had to read all of them and investigate additionally for a while to display a date time string from db in a user's local timezone format.

我将到目前为止的答案混合在一起,并添加到其中,因为我必须阅读所有答案,并对它们进行额外的研究,以便以用户的本地时区格式显示来自db的日期时间字符串。

The datetime string comes from a python/django db in the format: 2016-12-05T15:12:24.215Z

datetime字符串来自于python/django db格式:2016-12-05T15:12:24.215Z。

Reliable detection of the browser language in JavaScript doesn't seem to work in all browsers (see JavaScript for detecting browser language preference), so I get the browser language from the server.

对JavaScript中浏览器语言的可靠检测似乎并不适用于所有浏览器(请参阅JavaScript以检测浏览器语言偏好),因此我从服务器获得浏览器语言。

Python/Django: send request browser language as context parameter:

Python/Django:将请求浏览器语言作为上下文参数发送:

language = request.META.get('HTTP_ACCEPT_LANGUAGE')
return render(request, 'cssexy/index.html', { "language": language })

HTML: write it in a hidden input:

HTML:写在一个隐藏的输入:

<input type="hidden" id="browserlanguage" value={{ language }}/>

JavaScript: get value of hidden input e.g. en-GB,en-US;q=0.8,en;q=0.6/ and then take the first language in the list only via replace and regular expression

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");

JavaScript: convert to datetime and format it:

JavaScript:转换到datetime并格式化它:

var options = { hour: "2-digit", minute: "2-digit" };
var dt = (new Date(str)).toLocaleDateString(defaultlang, options);

See: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString

参见:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString

The result is (browser language is en-gb): 05/12/2016, 14:58

结果是(浏览器语言为en-gb): 05/12/2016, 14:58

#9


2  

The best solution I've come across is to create [time display="llll" datetime="UTC TIME" /] Tags, and use javascript (jquery) to parse and display it relative to the user's time.

我遇到的最好的解决方案是创建[time display="llll" datetime="UTC time " /]标签,并使用javascript (jquery)来解析和显示它相对于用户的时间。

http://momentjs.com/ Moment.js

http://momentjs.com/ Moment.js

will display the time nicely.

会很好地显示时间。

#10


2  

You could use the following, which reports the timezone offset from GMT in minutes:

您可以使用下面的方法,它报告了时区从格林尼治时间到分钟的偏移量:

new Date().getTimezoneOffset();

Note : - this function return a negative number.

注意:-这个函数返回一个负数。

#11


1  

getTimeZoneOffset() and toLocaleString are good for basic date work, but if you need real timezone support, look at mde's TimeZone.js.

getTimeZoneOffset()和toLocaleString非常适合基本的日期工作,但是如果您需要真正的时区支持,请查看mde的timezone .js。

There's a few more options discussed in the answer to this question

在这个问题的答案中,我们还讨论了一些选项

#12


1  

In JS there are no simple and cross platform ways to format local date time, outside of converting each property as mentioned above.

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

Here is a quick hack I use to get the local YYYY-MM-DD. Note that this is a hack, as the final date will not have the correct timezone anymore (so you have to ignore timezone). If I need anything else more, I use moment.js.

这里有一个我用来获取本地yyyyy - mm - dd的快速技巧。注意,这是一个技巧,因为最终的日期将不再具有正确的时区(因此必须忽略时区)。如果我还需要什么,我就用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)

The d.getTimezoneOffset() returns the time zone offset in minutes, and the d.getTime() is in ms, hence the x 60,000.

d.getTimezoneOffset()返回时间区域以分钟为单位的偏移量,而d.getTime()是在ms中,因此是x 60000。

#13


-8  

Don't know how to do locale, but javascript is a client side technology.

不知道如何进行语言环境,但是javascript是客户端技术。

usersLocalTime = new Date();

will have the client's time and date in it (as reported by their browser, and by extension the computer they are sitting at). It should be trivial to include the server's time in the response and do some simple math to guess-timate offset.

将客户的时间和日期包含在其中(由他们的浏览器报告,并扩展到他们所在的计算机)。在响应中包含服务器的时间,并做一些简单的计算来猜测估计值,这应该是微不足道的。