简体   繁体   English

Javascript将字符串转换为ISO日期

[英]Javascript convert String to ISO Date

i want to parse an Date String into the ISO Format. 我想将日期字符串解析为ISO格式。 Sometimes it work sometimes not. 有时它有时不起作用。

                            //17.08.2016 00:23:51 doesent work
                            //01.08.2016 00:05:32 work
                            var ParsedData = "COPY FROM ABOVE";

                            console.log("#####Start Date converstion########");
                            console.log("BEFORE Parsed Date: -" + ParsedData + "-");
                            tempdate = new Date(ParsedData);
                            console.log("AFTER Parsed Date: " + tempdate);
                            tempdate = tempdate.toISOString();
                            console.log("ISO Parsed Date: " + tempdate);
                          } catch (e) {
                            console.log(e);
                            if (e instanceof TypeError) {
                              //console.log(e);
                            }
                            else if(e instanceof RangeError) {
                              tempdate = ParsedDate
                            }
                            else {
                               console.log("Error not catched: " + e);
                            }
                          }

                          console.log("Parsed Date: " + tempdate);
                          console.log("#####END Date converstion########");

Produces: 产生:

Start Date converstion 开始日期对话

BEFORE Parsed Date: 17.08.2016 00:23:51 AFTER Parsed Date: Invalid Date Parsed Date: 17.08.2016 00:23:51 解析日期之前:17.08.2016 00:23:51解析日期之后:无效日期解析日期:17.08.2016 00:23:51

END Date converstion Start Date converstion 结束日期对话开始日期对话

BEFORE Parsed Date: 01.08.2016 00:19:02 AFTER Parsed Date: Fri Jan 08 2016 00:19:02 GMT+0100 (CET) ISO Parsed Date: 2016-01-07T23:19:02.000Z Parsed Date: 2016-01-07T23:19:02.000Z 解析日期之前:01.08.2016 00:19:02之后解析日期:2016年1月8日星期五格林尼治标准时间+0100(CET)ISO解析日期:2016-01-07T23:19:02.000Z解析日期:2016- 01-07T23:19:02.000Z

END Date converstion 结束日期对话

i have no clue why. 我不知道为什么。 i hope somebody can tell me why. 我希望有人能告诉我原因。

Regards 问候

Date.parse

It is not recommended to use Date.parse as until ES5, parsing of strings was entirely implementation dependent. 在ES5之前,不建议使用Date.parse,因为字符串的解析完全取决于实现。 There are still many differences in how different hosts parse date strings, therefore date strings should be manually parsed (a library can help if many different formats are to be accommodated). 不同主机解析日期字符串的方式仍存在许多差异,因此应手动解析日期字符串(如果要容纳许多不同格式,则库可以提供帮助)。

An example of parsing the strings yourself. 自己解析字符串的示例。

 var datetimes = ['17.08.2016 00:23:51', '01.08.2016 00:05:32']; datetimes.forEach(function(datetime) { var dateAndTime = datetime.split(' '); var date = dateAndTime[0].split('.').reverse(); // month is zero indexed date[1] -= 1; var time = dateAndTime[1].split(':'); // assuming datetimes are UTC dateAndTime = new Date(Date.UTC.apply(null, date.concat(time))).toISOString(); // if not UTC but local //dateAndTime = new Date(date[0], date[1], date[2], time[0], time[1], time[2]).toISOString(); console.log(dateAndTime); }); 

Alternatively, if the original strings are already UTC then you could just manipulate the strings and not use Date at all. 或者,如果原始字符串已经是UTC,那么您可以操作这些字符串而根本不使用Date

 var datetimes = ['17.08.2016 00:23:51', '01.08.2016 00:05:32']; datetimes.forEach(function(datetime) { var dateAndTime = datetime.split(' '); var date = dateAndTime[0].split('.').reverse(); dateAndTime = date.join('-') + 'T' + dateAndTime[1] + '.000Z'; console.log(dateAndTime); }); 

Parsing strings with the Date constructor is strongly discouraged (as is using Date.parse as it is equivalent for parsing). 强烈建议不要使用Date构造函数来解析字符串(与使用Date.parse一样,因为它等效于解析)。 The format you're using is not one that is supported by ECMA-262 so parsing is entirely implementation dependent. 您使用的格式不是ECMA-262支持的格式,因此解析完全取决于实现。 Even the formats in the language specification are not consistently supported by browsers in use so either use a bespoke function or a library. 使用的浏览器甚至都不统一支持语言规范中的格式,因此请使用定制功能或库。

Since the date and time does not have any timezone information, it should be treated as local. 由于日期和时间没有任何时区信息,因此应将其视为本地时间。

Once you've parsed the string to a Date, you can use toISOString to get the required format, noting that it will always return the date and time as UTC. 将字符串解析为日期后,可以使用toISOString获取所需的格式,请注意,它将始终以UTC返回日期和时间。

 /* Parse string in DD.MM.YYYY HH:mm:ss format ** @param {string} s - string to parse ** @returns {Date} if string has invalid date components, ** an invalid Date is returned */ function parseString(s) { var b = s.split(/\\D/); var d = new Date(b[2], --b[1], b[0], b[3], b[4], b[5]); return d && d.getMonth() == b[1] && d.getHours() == b[3] && d.getMinutes() == b[4]? d : new Date(NaN); } console.log(parseString('17.08.2016 00:23:51').toISOString()); console.log(parseString('01.08.2016 00:05:32').toISOString()); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM