假设您网站的用户输入了一个日期范围。

2009-1-1 to 2009-1-3

您需要将此日期发送到服务器进行某些处理,但服务器要求所有日期和时间均为UTC。

现在假设用户在阿拉斯加。由于它们所处的时区与UTC完全不同,因此需要将日期范围转换为如下所示:

2009-1-1T8:00:00 to 2009-1-4T7:59:59

使用JavaScriptDate对象,如何将第一个“本地化”日期范围转换为服务器能够理解的内容?


当前回答

如果需要日期对象

仅传递日期字符串date假定时间按时区偏移00:00:

new Date('2019-03-11')
Sun Mar 10 2019 18:00:00 GMT-0600 (Central Standard Time)

如果您添加当前的小时和分钟,您将获得正确的日期:

new Date('2019-03-11 ' + new Date().getHours() + ':' + new Date().getMinutes())
Mon Mar 11 2019 04:36:00 GMT-0600 (Central Standard Time)

其他回答

该方法将为您提供:2017-08-04T11:15:00.000+04:30,您可以忽略区域变量,只需获得2017-08-04T1 1:15:00.000。

function getLocalIsoDateTime(dtString) {
    if(dtString == "")
        return "";
    var offset = new Date().getTimezoneOffset();
    var localISOTime = (new Date(new Date(dtString) - offset * 60000 /*offset in milliseconds*/)).toISOString().slice(0,-1);
    //Next two lines can be removed if zone isn't needed.
    var absO = Math.abs(offset);
    var zone = (offset < 0 ? "+" : "-") + ("00" + Math.floor(absO / 60)).slice(-2) + ":" + ("00" + (absO % 60)).slice(-2);
    return localISOTime + zone;
}

根据我的观察,

var timeUtc=新日期();

timeUtc将始终显示UTC时间,但如果您调试或控制台,浏览器将始终显示当前时区的时间。

如果您将timeUtc作为参数发送到任何post请求,那么在chrome的网络选项卡中,您可以检查post数据,您将看到timeUtc将具有UTC时间。

对于目标是将其作为“日期对象”而不是字符串获取的其他人,并且您只想显示不带TZ(可能是硬编码的)的日期/时间,您可以做的是:

const now = new Date();
const year = now.getUTCFullYear();
const month = now.getUTCMonth();
const day = now.getUTCDate();
const hour = now.getUTCHours();

const tomorrowUTC= new Date();
tomorrowUTC.setDate(day + 1); // +1 because my logic is to get "tomorrow"
tomorrowUTC.setYear(year);
tomorrowUTC.setMonth(month);
tomorrowUTC.Hours(hour);

// then use the tomorrowUTC for to display/format it
// tomorrowUTC is a "Date" and not a string.

然后,您可以执行以下操作:

我们将在${格式(明天UTC,'EEEE do MMMM hh:mmaa')}UTC删除您的帐户

(格式是一个日期fns函数,如果需要,可以使用其他lib);

这有点“黑客”,因为这仍然使用本地时区,但如果你只想显示日期而不是时区,那么这就可以了。

这是我过去所做的:

var utcDateString = new Date(new Date().toUTCString()).toISOString();

使用moment包,您可以轻松地将UTC的日期字符串转换为新的date对象:

const moment = require('moment');
let b = new Date(moment.utc('2014-02-20 00:00:00.000000'));
let utc = b.toUTCString();
b.getTime();

当您的服务器不支持时区,并且您希望将UTC日期始终存储在服务器中,并将其作为新的日期对象取回时,这特别有用。以上代码适用于我的需求,也适用于本线程的类似问题。在这里分享,这样可以帮助其他人。我在任何答案中都看不到上述解决方案。谢谢