将 ISO 日期字符串更改为日期对象 - JavaScript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27012854/
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
Change ISO Date String to Date Object - JavaScript
提问by Mohit Pandey
I am stuck in a weird situation and unfortunately,even after doing some RnD and googling, i am unable to solve this problem.
我陷入了一个奇怪的境地,不幸的是,即使做了一些 RnD 和谷歌搜索,我也无法解决这个问题。
I have a date string in ISO format, like 2014-11-03T19:38:34.203Zand i want to convert it into a date object with new Date()method.
我有一个 ISO 格式的日期字符串,就像2014-11-03T19:38:34.203Z我想用new Date()方法将它转换成一个日期对象 。
But when i do so, output is:
但是当我这样做时,输出是:
var isoDate = '2014-11-03T19:38:34.203Z';
console.log(new Date(isoDate)); //output is: Tue Nov 04 2014 01:08:34 GMT+0530 (IST)
The date which i passed is of 3 Nov,2014and the output is 4 Nov,2014and it's because of GMT +5.30 of our local time(IST).
我通过的日期是,3 Nov,2014输出是4 Nov,2014,这是因为我们当地时间(IST)的格林威治标准时间 +5.30。
So, is there any generic method with which i can get the dateobject which return the date of Nov 3,2014.
那么,是否有任何通用方法可以让我获得date返回日期的对象Nov 3,2014。
NOTE: I don't have any issues with timestamp. We can change time string to zero with setHours()method. The only thing which i want is dateobject like new Date()having date of 3 Nov,2014.
注意:我对时间戳没有任何问题。我们可以使用setHours()方法将时间字符串更改为零。我唯一想要的是date对象,例如new Date()日期为3 Nov,2014.
采纳答案by RobG
Do not pass strings to the Date constructor, it is notoriously bad at parsing strings. IE 8, for one, will not parse ISO 8601 format strings at all and return NaN. It's really simple to write your own parser:
不要将字符串传递给 Date 构造函数,它在解析字符串方面是出了名的糟糕。例如,IE 8 根本不会解析 ISO 8601 格式字符串并返回NaN。编写自己的解析器非常简单:
function parseISOString(s) {
var b = s.split(/\D+/);
return new Date(Date.UTC(b[0], --b[1], b[2], b[3], b[4], b[5], b[6]));
}
Note also that if the time is 19:38:34.203 UTC and your timezone is UTC +0530, then the time in that timezone is 01:08:34 am on the following day, hence the difference in dates. For example, for a person on the east coast of Australia but not observing daylight saving (i.e. UTC +10), it's equivalent to:
另请注意,如果时间是 19:38:34.203 UTC 而您的时区是 UTC +0530,那么该时区中的时间是第二天上午 01:08:34,因此日期不同。例如,对于一个在澳大利亚东海岸但不遵守夏令时(即UTC+10)的人,相当于:
4 November, 2014 05:38:34
Edit
编辑
So if you want to return it to an ISO date, you can use the getISO*methods to create whatever format that suits, e.g.
因此,如果您想将其返回到 ISO 日期,您可以使用getISO*方法来创建适合的任何格式,例如
function isoFormatDMY(d) {
function pad(n) {return (n<10? '0' : '') + n}
return pad(d.getUTCDate()) + '/' + pad(d.getUTCMonth() + 1) + '/' + d.getUTCFullYear();
}
var s = '2014-11-03T19:38:34.203Z';
var date = parseISOString(s);
console.log(isoFormatDMY(date)) // 03/11/2014
or use ES5's toISOString:
或使用 ES5 的toISOString:
parseISOString('2014-11-03T19:38:34.203Z').toISOString(); // 2014-11-03T19:38:34.203Z
A simple polyfill for pre ES5 browsers:
ES5 之前的浏览器的简单 polyfill:
if (!Date.prototype.toISOString) {
Date.prototype.toISOString = function() {
var d = this;
// Padding functions
function pad(n) {return (n<10? '0' : '') + n}
function padd(n){return (n<100? '0' : '') + pad(n)}
return d.getUTCFullYear() + '-' + pad(d.getUTCMonth() + 1) + '-' + pad(d.getUTCDate()) +
'T' + pad(d.getUTCHours()) + ':' + pad(d.getUTCMinutes()) + ':' +
pad(d.getUTCSeconds()) + '.' + padd(d.getMilliseconds()) + 'Z';
}
}
回答by Prabhu Vignesh Rajagopal
You can use "getUTCDate()" to get actual date.
您可以使用“getUTCDate()”来获取实际日期。
var d = new Date('2014-11-03T19:38:34.203Z');
var n = d.getUTCDate();
But it will return only date. to get month "getUTCMonth()" and to get year "getUTCFullYear()". Then construct all in to your format. For example
但它只会返回日期。获得月份“getUTCMonth()”并获得年份“getUTCFullYear()”。然后按照您的格式构建所有内容。例如
var n=[];
var d = new Date('2014-11-03T19:38:34.203Z');
var s = d.getUTCDate();
n.push(s);
s=d.getUTCMonth();
n.push(s);
s=d.getUTCFullYear();
n.push(s);
finally make "n" as an object.
最后将“n”作为一个对象。
All the best
祝一切顺利
回答by CaptainDingle
I also did not care about timestamp/timezone as I am returning only dates from SQL in ISO format. To avoid the day being either one ahead or one behind when converting to Date object, this works:
我也不关心时间戳/时区,因为我只返回 ISO 格式的 SQL 日期。为了避免在转换为 Date 对象时一天前一天或后一天,这有效:
moment(ISOStringHere, 'YYYY-MM-DD HH:mm'); // leaving off Z makes it UTC to match database
This requires the Moment JS library located here:
这需要位于此处的 Moment JS 库:
回答by kevinmicke
Here's a function that works well for those that need to support older browsers and adjust correctly for timezones in the date strings. I used RobG's answeras a starting point, but had to modify it heavily because it wasn't working for me with strings that had offsets for the timezone like "-07:00" (i.e. strings that don't end in "Z").
这是一个非常适合需要支持旧浏览器并正确调整日期字符串中的时区的功能。我使用RobG 的答案作为起点,但不得不对其进行大量修改,因为它不适用于具有时区偏移量的字符串,例如“-07:00”(即不以“Z”结尾的字符串) )。
// Parse an ISO date string (i.e. "2019-01-18T00:00:00.000Z",
// "2019-01-17T17:00:00.000-07:00", or "2019-01-18T07:00:00.000+07:00",
// which are the same time) and return a JavaScript Date object with the
// value represented by the string.
function isoStringToDate( isoString ) {
// Split the string into an array based on the digit groups.
var dateParts = isoString.split( /\D+/ );
// Set up a date object with the current time.
var returnDate = new Date();
// Manually parse the parts of the string and set each part for the
// date. Note: Using the UTC versions of these functions is necessary
// because we're manually adjusting for time zones stored in the
// string.
returnDate.setUTCFullYear( parseInt( dateParts[ 0 ] ) );
// The month numbers are one "off" from what normal humans would expect
// because January == 0.
returnDate.setUTCMonth( parseInt( dateParts[ 1 ] - 1 ) );
returnDate.setUTCDate( parseInt( dateParts[ 2 ] ) );
// Set the time parts of the date object.
returnDate.setUTCHours( parseInt( dateParts[ 3 ] ) );
returnDate.setUTCMinutes( parseInt( dateParts[ 4 ] ) );
returnDate.setUTCSeconds( parseInt( dateParts[ 5 ] ) );
returnDate.setUTCMilliseconds( parseInt( dateParts[ 6 ] ) );
// Track the number of hours we need to adjust the date by based
// on the timezone.
var timezoneOffsetHours = 0;
// If there's a value for either the hours or minutes offset.
if ( dateParts[ 7 ] || dateParts[ 8 ] ) {
// Track the number of minutes we need to adjust the date by
// based on the timezone.
var timezoneOffsetMinutes = 0;
// If there's a value for the minutes offset.
if ( dateParts[ 8 ] ) {
// Convert the minutes value into an hours value.
timezoneOffsetMinutes = parseInt( dateParts[ 8 ] ) / 60;
}
// Add the hours and minutes values to get the total offset in
// hours.
timezoneOffsetHours = parseInt( dateParts[ 7 ] ) + timezoneOffsetMinutes;
// If the sign for the timezone is a plus to indicate the
// timezone is ahead of UTC time.
if ( isoString.substr( -6, 1 ) == "+" ) {
// Make the offset negative since the hours will need to be
// subtracted from the date.
timezoneOffsetHours *= -1;
}
}
// Get the current hours for the date and add the offset to get the
// correct time adjusted for timezone.
returnDate.setHours( returnDate.getHours() + timezoneOffsetHours );
// Return the Date object calculated from the string.
return returnDate;
}
Usage/a couple tests:
用法/几个测试:
// All three of these tests output the same date (relative to your
// timezone) as they should, which in my case is:
// "Thu Jan 17 2019 17:00:00 GMT-0700 (Mountain Standard Time)".
console.log( isoStringToDate( "2019-01-18T00:00:00.000Z" ) );
console.log( isoStringToDate( "2019-01-17T17:00:00.000-07:00" ) );
console.log( isoStringToDate( "2019-01-18T07:00:00.000+07:00" ) );
回答by Lashus
Well it depends on what you want to do with the object later. You can always refer to "UTC" date functions of javascript.
好吧,这取决于您以后要对对象做什么。您可以随时参考 javascript 的“UTC”日期函数。
Check the reference: 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
回答by Michal Filip
I started of with kevinmicke'sexcellent answer, but since I needed this for a code generator, I was concerned with code size. Eventually I ended up with this:
我从kevinmicke 的优秀答案开始,但由于我需要将其用于代码生成器,因此我担心代码大小。最终我得到了这个:
const parseDate = dateString => {
const b = dateString.split(/\D+/);
const offsetMult = dateString.indexOf('+') !== -1 ? -1 : 1;
const hrOffset = offsetMult * (+b[7] || 0);
const minOffset = offsetMult * (+b[8] || 0);
return new Date(Date.UTC(+b[0], +b[1] - 1, +b[2], +b[3] + hrOffset, +b[4] + minOffset, +b[5], +b[6] || 0));
};
回答by Akshay
new Date(this.datePipe.transform(isoDate,'yyyy-MM-dd HH:mm:ss', 'UTC'));
Angular datepipe transform will convert it to a simple date time format as specified with no timezone. In case of ISO string format, the date constructor would have treated it as UTC time, but now, the Date constructor treats it as the local time.
Angular datepipe 转换会将其转换为没有时区的简单日期时间格式。在 ISO 字符串格式的情况下,日期构造函数会将其视为 UTC 时间,但现在,日期构造函数将其视为本地时间。
Example in my case(IST):
我的例子(IST):
input string: 2020-04-19T09:15:00.000Z
after transform this.datePipe.transform(input string)
2020-04-19 09:15:00
Date object
new Date(this.datePipe.transform(isoDate,'yyyy-MM-dd HH:mm:ss', 'UTC'));//treats the transformed date as local timezone date when creating the date object
Sun Apr 19 2020 09:15:00 GMT+0530 (India Standard Time)
回答by AnweshCR7
For display purposes, you could simply do this... Given 'Date' in ISO format you could implement,
出于显示目的,您可以简单地执行此操作...给定 ISO 格式的“日期”,您可以实现,
<div> {{Date | date:"dd MMM yy hh:mm a" }} </div>
A nifty trick to display (only display) the date in required format.
以所需格式显示(仅显示)日期的绝妙技巧。
Hope it helps!
希望能帮助到你!

