javascript 解析没有时区的日期javascript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17545708/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 08:42:56  来源:igfitidea点击:

Parse date without timezone javascript

javascriptdatetimestamp-with-timezone

提问by Athlan

I want to parse date without timezone in JavaScript. I have tried:

我想在 JavaScript 中解析没有时区的日期。我努力了:

new Date(Date.parse("2005-07-08T00:00:00+0000"));

Returns Fri Jul 08 2005 02:00:00 GMT+0200(Central European Daylight Time)

返回 2005 年 7 月 8 日星期五 02:00:00 GMT+0200(中欧夏令时)

new Date(Date.parse("2005-07-08 00:00:00 GMT+0000"));

Returns same result

返回相同的结果

new Date(Date.parse("2005-07-08 00:00:00 GMT-0000"));

Returns same result

返回相同的结果

I want to parse time:

我想解析时间:

  1. Without time zone.

  2. Without calling constructor Date.UTC or new Date(year, month, day).

  3. Just simple passing string into Date constructor (without prototype approaches).

  4. I have to product Dateobject, not String.

  1. 没有时区。

  2. 不调用构造函数 Date.UTC 或 new Date(year, month, day)。

  3. 只是简单地将字符串传递给 Date 构造函数(没有原型方法)。

  4. 我必须生产Date对象,而不是String.

采纳答案by georg

The date is parsed correctly, it's just toString that converts it to your local timezone:

日期被正确解析,只是 toString 将其转换为您的本地时区:

let s = "2005-07-08T11:22:33+0000";
let d = new Date(Date.parse(s));

// this logs for me 
// "Fri Jul 08 2005 13:22:33 GMT+0200 (Central European Summer Time)" 
// and something else for you

console.log(d.toString()) 

// this logs
// Fri, 08 Jul 2005 11:22:33 GMT
// for everyone

console.log(d.toUTCString())

Javascript Date object are timestamps - they merely contain a number of milliseconds since the epoch. There is no timezone info in a Date object. Which calendar date (day, minutes, seconds) this timestamp represents is a matter of the interpretation (one of to...Stringmethods).

Javascript Date 对象是时间戳——它们只包含自纪元以来的毫秒数。Date 对象中没有时区信息。这个时间戳代表哪个日历日期(日、分、秒)是解释问题(to...String方法之一)。

The above example shows that the date is being parsed correctly - that is, it actually contains an amount of milliseconds corresponding to "2005-07-08T11:22:33" in GMT.

上面的例子表明日期被正确解析——也就是说,它实际上包含了对应于格林威治标准时间“2005-07-08T11:22:33”的毫秒数。

回答by wawka

I have the same issue. I get a date as a String, for example: '2016-08-25T00:00:00', but I need to have Date object with correct time. To convert String into object, I use getTimezoneOffset:

我有同样的问题。我得到一个字符串形式的日期,例如:'2016-08-25T00:00:00',但我需要有正确时间的日期对象。要将 String 转换为对象,我使用 getTimezoneOffset:

var date = new Date('2016-08-25T00:00:00')
var userTimezoneOffset = date.getTimezoneOffset() * 60000;
new Date(date.getTime() - userTimezoneOffset);

getTimezoneOffset()will return ether negative or positive value. This must be subtracted to work in every location in world.

getTimezoneOffset()将返回以太负值或正值。必须减去它才能在世界上的每个位置工作。

回答by Iwnnay

I ran into the same problem and then remembered something wonky about a legacy project I was working on and how they handled this issue. I didn't understand it at the time and didn't really care until I ran into the problem myself

我遇到了同样的问题,然后想起了我正在处理的遗留项目以及他们如何处理这个问题的一些奇怪的事情。我当时不明白,也没有真正在意,直到我自己遇到了问题

var date = '2014-01-02T00:00:00.000Z'
date = date.substring(0,10).split('-')
date = date[1] + '-' + date[2] + '-' + date[0]

new Date(date) #Thu Jan 02 2014 00:00:00 GMT-0600

For whatever reason passing the date in as '01-02-2014' sets the timezone to zero and ignores the user's timezone. This may be a fluke in the Date class but it existed some time ago and exists today. And it seems to work cross-browser. Try it for yourself.

无论出于何种原因,将日期作为 '01-02-2014' 传入都会将时区设置为零并忽略用户的时区。这可能是 Date 类中的侥幸,但它在前一段时间存在并存在于今天。它似乎可以跨浏览器工作。自己试试吧。

This code is implemented in a global project where timezones matter a lot but the person looking at the date did not care about the exact moment it was introduced.

这段代码是在一个全球项目中实现的,其中时区很重要,但查看日期的人并不关心它被引入的确切时间。

回答by mishik

The Dateobject itself will contain timezone anyway, and the returned result is the effect of converting it to string in a default way. I.e. you cannot create a date object withouttimezone. But what you can do is mimic the behavior of Dateobject by creating your own one. This is, however, better to be handed over to libraries like moment.js.

Date对象本身将包含时区无论如何,返回的结果是一个默认的方式将其转换为字符串的效果。即你不能创建一个没有时区的日期对象。但是您可以做的是Date通过创建自己的对象来模仿对象的行为。但是,最好将其交给像moment.js这样的

回答by alexey

simple solution

简单的解决方案

const handler1 = {
  construct(target, args) {
    let newDate = new target(...args);
    var tzDifference = newDate.getTimezoneOffset();
    return new target(newDate.getTime() + tzDifference * 60 * 1000);
  }
};

Date = new Proxy(Date, handler1);

回答by D.R.Bendanillo

Date in javascript is just keeping it simple inside. so the date-time data is stored in UTC unix epoch (milliseconds or ms).

javascript 中的日期只是在内部保持简单。所以日期时间数据存储在 UTC unix 纪元(毫秒或毫秒)中。

If you want to have a "fixed" time that doesn't change in whatever timezone you are on the earth, you can adjust the time in UTC to match your current local timezone and save it. And when retreiving it, in whatever your local timezone you are in, it will show the adjusted UTC time based on the one who saved it and the add the local timezone offset to get the "fixed" time.

如果您想拥有一个在地球上的任何时区都不会改变的“固定”时间,您可以调整 UTC 时间以匹配您当前的本地时区并保存它。并且在检索它时,无论您在哪个本地时区,它都会根据保存它的人显示调整后的 UTC 时间,并添加本地时区偏移量以获得“固定”时间。

To save date (in ms)

保存日期(以毫秒为单位)

toUTC(datetime) {
  const myDate = (typeof datetime === 'number')
    ? new Date(datetime)
    : datetime;

  if (!myDate || (typeof myDate.getTime !== 'function')) {
    return 0;
  }

  const getUTC = myDate.getTime();
  const offset = myDate.getTimezoneOffset() * 60000; // It's in minutes so convert to ms
  return getUTC - offset; // UTC - OFFSET
}

To retreive/show date (in ms)

检索/显示日期(以毫秒为单位)

fromUTC(datetime) {
  const myDate = (typeof datetime === 'number')
    ? new Date(datetime)
    : datetime;

  if (!myDate || (typeof myDate.getTime !== 'function')) {
    return 0;
  }

  const getUTC = myDate.getTime();
  const offset = myDate.getTimezoneOffset() * 60000; // It's in minutes so convert to ms
  return getUTC + offset; // UTC + OFFSET
}

Then you can:

那么你也能:

const saveTime = new Date(toUTC(Date.parse("2005-07-08T00:00:00+0000")));
// SEND TO DB....

// FROM DB...
const showTime = new Date(fromUTC(saveTime));

回答by John Galt

Since it is really a formatting issue when displaying the date (e.g. displays in local time), I like to use the new(ish) Intl.DateTimeFormatobject to perform the formatting as it is more explicit and provides more output options:

由于在显示日期时确实是格式问题(例如在本地时间显示),我喜欢使用 new(ish) Intl.DateTimeFormat对象来执行格式,因为它更明确并提供更多输出选项:

const dateOptions = { timeZone: 'UTC', month: 'long', day: 'numeric', year: 'numeric' };

const dateFormatter = new Intl.DateTimeFormat('en-US', dateOptions);
const dateAsFormattedString = dateFormatter.format(new Date('2019-06-01T00:00:00.000+00:00'));

console.log(dateAsFormattedString) // "June 1, 2019"

As shown, by setting the timeZone to 'UTC' it will not perform local conversions. As a bonus, it also allows you to create more polished outputs. You can read more about the Intl.DateTimeFormatobject from Mozilla - Intl.DateTimeFormat.

如图所示,通过将时区设置为“UTC”,它不会执行本地转换。作为奖励,它还允许您创建更精美的输出。您可以从Mozilla - Intl.DateTimeFormat阅读有关Intl.DateTimeFormat对象的更多信息。

回答by deype0

You can use this code

您可以使用此代码

var stringDate = "2005-07-08T00:00:00+0000";
var dTimezone = new Date();
var offset = dTimezone.getTimezoneOffset() / 60;
var date = new Date(Date.parse(stringDate));
date.setHours(date.getHours() + offset);

回答by NVRM

Just a generic note. a way to keep it flexible.

只是一个通用的注释。一种保持灵活性的方法。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

We can use getMinutes(), but it return only one number for the first 9 minutes.

我们可以使用 getMinutes(),但它在前 9 分钟只返回一个数字。

let epoch = new Date() // Or any unix timestamp

let za = new Date(epoch),
    zaR = za.getUTCFullYear(),
    zaMth = za.getUTCMonth(),
    zaDs = za.getUTCDate(),
    zaTm = za.toTimeString().substr(0,5);

console.log(zaR +"-" + zaMth + "-" + zaDs, zaTm)

Date.prototype.getDate()
    Returns the day of the month (1-31) for the specified date according to local time.
Date.prototype.getDay()
    Returns the day of the week (0-6) for the specified date according to local time.
Date.prototype.getFullYear()
    Returns the year (4 digits for 4-digit years) of the specified date according to local time.
Date.prototype.getHours()
    Returns the hour (0-23) in the specified date according to local time.
Date.prototype.getMilliseconds()
    Returns the milliseconds (0-999) in the specified date according to local time.
Date.prototype.getMinutes()
    Returns the minutes (0-59) in the specified date according to local time.
Date.prototype.getMonth()
    Returns the month (0-11) in the specified date according to local time.
Date.prototype.getSeconds()
    Returns the seconds (0-59) in the specified date according to local time.
Date.prototype.getTime()
    Returns the numeric value of the specified date as the number of milliseconds since January 1, 1970, 00:00:00 UTC (negative for prior times).
Date.prototype.getTimezoneOffset()
    Returns the time-zone offset in minutes for the current locale.
Date.prototype.getUTCDate()
    Returns the day (date) of the month (1-31) in the specified date according to universal time.
Date.prototype.getUTCDay()
    Returns the day of the week (0-6) in the specified date according to universal time.
Date.prototype.getUTCFullYear()
    Returns the year (4 digits for 4-digit years) in the specified date according to universal time.
Date.prototype.getUTCHours()
    Returns the hours (0-23) in the specified date according to universal time.
Date.prototype.getUTCMilliseconds()
    Returns the milliseconds (0-999) in the specified date according to universal time.
Date.prototype.getUTCMinutes()
    Returns the minutes (0-59) in the specified date according to universal time.
Date.prototype.getUTCMonth()
    Returns the month (0-11) in the specified date according to universal time.
Date.prototype.getUTCSeconds()
    Returns the seconds (0-59) in the specified date according to universal time.
Date.prototype.getYear()
    Returns the year (usually 2-3 digits) in the specified date according to local time. Use getFullYear() instead. 

回答by saran3h

This is the solution that I came up with for this problem which works for me.

这是我为这个问题想出的解决方案,它对我有用。



library used: momentjs with plain javascript Date class.

使用的库:momentjs 与纯 javascript Date 类。

Step 1. Convert String date to moment object (PS: moment retains the original date and time as long as toDate()method is not called):

Step 1. 将String日期转换为moment对象(PS:只要toDate()不调用方法,moment就会保留原来的日期和时间):

const dateMoment = moment("2005-07-08T11:22:33+0000");

const dateMoment = moment("2005-07-08T11:22:33+0000");

Step 2. Extract hoursand minutesvalues from the previously created moment object:

步骤 2.从先前创建的矩对象中提取hoursminutes取值:

  const hours = dateMoment.hours();
  const mins = dateMoment.minutes();

Step 3. Convert moment to Date(PS: this will change the original date based on the timezone of your browser/machine, but don't worry and read step 4.):

第 3 步。将时刻转换为日期(PS:这将根据您的浏览器/机器的时区更改原始日期,但不要担心并阅读第 4 步。):

  const dateObj = dateMoment.toDate();

Step 4. Manually set the hours and minutes extracted in Step 2.

步骤 4. 手动设置在步骤 2 中提取的小时和分钟。

  dateObj.setHours(hours);
  dateObj.setMinutes(mins);

Step 5. dateObjwill now have show the original Date without any timezone difference. Even the Daylight time changes won't have any effect on the date object as we are manually setting the original hours and minutes.

步骤 5. dateObj现在将显示没有任何时区差异的原始日期。即使是夏令时更改也不会对日期对象产生任何影响,因为我们是手动设置原始小时和分钟的。

Hope this helps.

希望这可以帮助。