在JavaScript中解析字符串到日期

发布于 2025-01-19 14:23:33 字数 200 浏览 1 评论 0 原文

如何在 JavaScript 中将字符串转换为 Date 对象?

var st = "date in some format"
var dt = new Date();

var dt_st = // st in Date format, same as dt.

How can I convert a string to a Date object in JavaScript?

var st = "date in some format"
var dt = new Date();

var dt_st = // st in Date format, same as dt.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

初雪 2025-01-26 14:23:33

字符串解析的最佳字符串格式是日期 ISO 格式以及 JavaScript Date 对象构造函数。

ISO 格式示例:YYYY-MM-DDYYYY-MM-DDTHH:MM:SS

但是等等!仅使用“ISO 格式”本身并不能可靠地工作。字符串有时被解析为 UTC,有时被解析为本地时间(基于浏览器供应商和版本)。最佳实践应始终是将日期存储为 UTC 并按 UTC 进行计算。

要将日期解析为 UTC,请附加 Z - 例如:new Date('2011-04-11T10:20:30Z')

要显示 UTC 日期,请使用 .toUTCString(),
要显示用户当地时间的日期,请使用 .toString()

有关 MDN | 的更多信息日期此答案

为了兼容旧版 Internet Explorer(小于 9 的 IE 版本不支持日期构造函数中的 ISO 格式),您应该将日期时间字符串表示形式拆分为其各个部分,然后您可以使用日期时间部分来使用构造函数,例如: new Date('2011 '、'04' - 1、'11'、'11'、'51'、'00')。请注意,月份数必须少 1。


替代方法 - 使用适当的库:

您还可以利用库 Moment.js允许解析具有指定时区的日期。

The best string format for string parsing is the date ISO format together with the JavaScript Date object constructor.

Examples of ISO format: YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS.

But wait! Just using the "ISO format" doesn't work reliably by itself. String are sometimes parsed as UTC and sometimes as localtime (based on browser vendor and version). The best practice should always be to store dates as UTC and make computations as UTC.

To parse a date as UTC, append a Z - e.g.: new Date('2011-04-11T10:20:30Z').

To display a date in UTC, use .toUTCString(),
to display a date in user's local time, use .toString().

More info on MDN | Date and this answer.

For old Internet Explorer compatibility (IE versions less than 9 do not support ISO format in Date constructor), you should split datetime string representation to it's parts and then you can use constructor using datetime parts, e.g.: new Date('2011', '04' - 1, '11', '11', '51', '00'). Note that the number of the month must be 1 less.


Alternate method - use an appropriate library:

You can also take advantage of the library Moment.js that allows parsing date with the specified time zone.

独享拥抱 2025-01-26 14:23:33

不幸的是我发现

var mydate = new Date('2014-04-03');
console.log(mydate.toDateString());

返回“2014 年 4 月 2 日星期三”。我知道这听起来很疯狂,但它发生在某些用户身上。

防弹解决方案如下:

var parts ='2014-04-03'.split('-');
// Please pay attention to the month (parts[1]); JavaScript counts months from 0:
// January - 0, February - 1, etc.
var mydate = new Date(parts[0], parts[1] - 1, parts[2]); 
console.log(mydate.toDateString());

Unfortunately I found out that

var mydate = new Date('2014-04-03');
console.log(mydate.toDateString());

returns "Wed Apr 02 2014". I know it sounds crazy, but it happens for some users.

The bulletproof solution is the following:

var parts ='2014-04-03'.split('-');
// Please pay attention to the month (parts[1]); JavaScript counts months from 0:
// January - 0, February - 1, etc.
var mydate = new Date(parts[0], parts[1] - 1, parts[2]); 
console.log(mydate.toDateString());

温柔少女心 2025-01-26 14:23:33
var st = "26.04.2013";
var pattern = /(\d{2})\.(\d{2})\.(\d{4})/;
var dt = new Date(st.replace(pattern,'$3-$2-$1'));

输出将是:

dt => Date {Fri Apr 26 2013}
var st = "26.04.2013";
var pattern = /(\d{2})\.(\d{2})\.(\d{4})/;
var dt = new Date(st.replace(pattern,'$3-$2-$1'));

And the output will be:

dt => Date {Fri Apr 26 2013}
晚雾 2025-01-26 14:23:33
function stringToDate(_date,_format,_delimiter)
{
            var formatLowerCase=_format.toLowerCase();
            var formatItems=formatLowerCase.split(_delimiter);
            var dateItems=_date.split(_delimiter);
            var monthIndex=formatItems.indexOf("mm");
            var dayIndex=formatItems.indexOf("dd");
            var yearIndex=formatItems.indexOf("yyyy");
            var month=parseInt(dateItems[monthIndex]);
            month-=1;
            var formatedDate = new Date(dateItems[yearIndex],month,dateItems[dayIndex]);
            return formatedDate;
}

stringToDate("17/9/2014","dd/MM/yyyy","/");
stringToDate("9/17/2014","mm/dd/yyyy","/")
stringToDate("9-17-2014","mm-dd-yyyy","-")
function stringToDate(_date,_format,_delimiter)
{
            var formatLowerCase=_format.toLowerCase();
            var formatItems=formatLowerCase.split(_delimiter);
            var dateItems=_date.split(_delimiter);
            var monthIndex=formatItems.indexOf("mm");
            var dayIndex=formatItems.indexOf("dd");
            var yearIndex=formatItems.indexOf("yyyy");
            var month=parseInt(dateItems[monthIndex]);
            month-=1;
            var formatedDate = new Date(dateItems[yearIndex],month,dateItems[dayIndex]);
            return formatedDate;
}

stringToDate("17/9/2014","dd/MM/yyyy","/");
stringToDate("9/17/2014","mm/dd/yyyy","/")
stringToDate("9-17-2014","mm-dd-yyyy","-")
初雪 2025-01-26 14:23:33

建议:我建议使用包含很多格式的日期包,因为时区和格式时间管理确实是一个大问题,moment js解决了很多格式。您可以轻松地从简单的字符串解析日期到日期,但我认为支持所有格式和日期变体是一项艰巨的工作。

更新:Moment 现已弃用,一个不错的替代方案目前是 datefns https://date-fns.org/


moment.js (http://momentjs.com/) 是一个完整且良好的使用日期包,支持 ISO 8601 字符串

您可以添加字符串日期和格式。

moment("12-25-1995", "MM-DD-YYYY");

您可以检查日期是否有效。

moment("not a real date").isValid(); //Returns false

一些显示示例

let dt = moment("02-01-2019", "MM-DD-YYYY");
console.log(dt.fromNow()+' |'+dt.format('LL')) 
// output: "3 months ago | February 1, 2019"

请参阅文档
http://momentjs.com/docs/#/parsing/string-format/

Recommendation: I recommend to use a package for dates that contains a lot of formats because the timezone and format time management is really a big problem, moment js solve a lot of formats. You could parse easily date from a simple string to date but I think that is a hard work to support all formats and variations of dates.

Update: Moment is now deprecated, A good alternative for moment is datefns https://date-fns.org/


moment.js (http://momentjs.com/) is a complete and good package for use dates and supports ISO 8601 strings.

You could add a string date and format.

moment("12-25-1995", "MM-DD-YYYY");

And you could check if a date is valid.

moment("not a real date").isValid(); //Returns false

Some display examples

let dt = moment("02-01-2019", "MM-DD-YYYY");
console.log(dt.fromNow()+' |'+dt.format('LL')) 
// output: "3 months ago | February 1, 2019"

See documentation
http://momentjs.com/docs/#/parsing/string-format/

人心善变 2025-01-26 14:23:33

将其作为参数传递给 Date():

var st = "date in some format"
var dt = new Date(st);

您可以使用以下方式访问日期、月份、年份:dt.getMonth()

Pass it as an argument to Date():

var st = "date in some format"
var dt = new Date(st);

You can access the date, month, year using, for example: dt.getMonth().

风情万种。 2025-01-26 14:23:33

只是 new Date(st);

假设它是正确格式

Just new Date(st);

Assuming that it's the proper format.

千纸鹤带着心事 2025-01-26 14:23:33

对于那些正在寻找小型智能解决方案的人:

String.prototype.toDate = function(format)
{
  var normalized      = this.replace(/[^a-zA-Z0-9]/g, '-');
  var normalizedFormat= format.toLowerCase().replace(/[^a-zA-Z0-9]/g, '-');
  var formatItems     = normalizedFormat.split('-');
  var dateItems       = normalized.split('-');

  var monthIndex  = formatItems.indexOf("mm");
  var dayIndex    = formatItems.indexOf("dd");
  var yearIndex   = formatItems.indexOf("yyyy");
  var hourIndex     = formatItems.indexOf("hh");
  var minutesIndex  = formatItems.indexOf("ii");
  var secondsIndex  = formatItems.indexOf("ss");

  var today = new Date();

  var year  = yearIndex>-1  ? dateItems[yearIndex]    : today.getFullYear();
  var month = monthIndex>-1 ? dateItems[monthIndex]-1 : today.getMonth()-1;
  var day   = dayIndex>-1   ? dateItems[dayIndex]     : today.getDate();

  var hour    = hourIndex>-1      ? dateItems[hourIndex]    : today.getHours();
  var minute  = minutesIndex>-1   ? dateItems[minutesIndex] : today.getMinutes();
  var second  = secondsIndex>-1   ? dateItems[secondsIndex] : today.getSeconds();

  return new Date(year,month,day,hour,minute,second);
};

示例:

"22/03/2016 14:03:01".toDate("dd/mm/yyyy hh:ii:ss");
"2016-03-29 18:30:00".toDate("yyyy-mm-dd hh:ii:ss");

For those who are looking for a tiny and smart solution:

String.prototype.toDate = function(format)
{
  var normalized      = this.replace(/[^a-zA-Z0-9]/g, '-');
  var normalizedFormat= format.toLowerCase().replace(/[^a-zA-Z0-9]/g, '-');
  var formatItems     = normalizedFormat.split('-');
  var dateItems       = normalized.split('-');

  var monthIndex  = formatItems.indexOf("mm");
  var dayIndex    = formatItems.indexOf("dd");
  var yearIndex   = formatItems.indexOf("yyyy");
  var hourIndex     = formatItems.indexOf("hh");
  var minutesIndex  = formatItems.indexOf("ii");
  var secondsIndex  = formatItems.indexOf("ss");

  var today = new Date();

  var year  = yearIndex>-1  ? dateItems[yearIndex]    : today.getFullYear();
  var month = monthIndex>-1 ? dateItems[monthIndex]-1 : today.getMonth()-1;
  var day   = dayIndex>-1   ? dateItems[dayIndex]     : today.getDate();

  var hour    = hourIndex>-1      ? dateItems[hourIndex]    : today.getHours();
  var minute  = minutesIndex>-1   ? dateItems[minutesIndex] : today.getMinutes();
  var second  = secondsIndex>-1   ? dateItems[secondsIndex] : today.getSeconds();

  return new Date(year,month,day,hour,minute,second);
};

Example:

"22/03/2016 14:03:01".toDate("dd/mm/yyyy hh:ii:ss");
"2016-03-29 18:30:00".toDate("yyyy-mm-dd hh:ii:ss");
神爱温柔 2025-01-26 14:23:33

如果您可以使用出色的 luxon 库库您可以轻松地使用EG来解析您的日期

var luxonDate = DateTime.fromISO("2014-09-15T09:00:00");

,并且可以访问您JS日期对象通过

luxonDate().toJSDate();

使用的旧答案

var momentDate = moment("2014-09-15 09:00:00");
momentDate ().toDate();

If you can use the terrific luxon library you can easily parse your date using e.g.

var luxonDate = DateTime.fromISO("2014-09-15T09:00:00");

and can access the JS date object via

luxonDate().toJSDate();

The old answer used MomentJS

var momentDate = moment("2014-09-15 09:00:00");
momentDate ().toDate();
昔日梦未散 2025-01-26 14:23:33

new Date(2000, 10, 1) 将为您提供“Wed Nov 01 2000 00:00:00 GMT+0100 (CET)”

请注意,月份 0 为您提供一月

new Date(2000, 10, 1) will give you "Wed Nov 01 2000 00:00:00 GMT+0100 (CET)"

See that 0 for month gives you January

他不在意 2025-01-26 14:23:33

在我看来,这是最好,更简单的解决方案:

只需加入日期字符串(使用 iso格式)最后,“ t00:00:00”最后使用 JavaScript Date()构造函数,如下所示。

const dateString = '2014-04-03'
var mydate = new Date(dateString + "T00:00:00");
console.log(mydate.toDateString());

仅有关上述解决方案的一些细节(但可选的阅读):

以ISO格式,如果您提供时间,并且z在末尾不存在
string,日期将是本地时区域UTC时间
区域
。这意味着,当设置
指定时区,JavaScript将使用本地浏览器的时间
区。当
获得日期,而无需指定时区域
同样,结果也将转换为浏览器的时区。和,
默认情况JavaScript中的方法(除了一个)
还为您提供当地时区的日期/时间(仅在
您指定UTC)。因此,在本地/浏览器时区使用您可能
不会获得不必要的结果,因为您的差异
本地/浏览时区和UTC时区,这是主要的
带有日期字符串转换的投诉。但是,如果您会使用这个
解决方案,了解您的上下文并了解您在做什么。
还要注意
省略t或z
可以在不同的浏览器中给出不同的结果。

重要的是要注意,上面的示例将为您提供以下示例的完全相同的返回,这是该问题中第二个选票的答案:

var parts ='2014-04-03'.split('-');
// Please pay attention to the month (parts[1]); JavaScript counts months from 0:
// January - 0, February - 1, etc.
var mydate = new Date(parts[0], parts[1] - 1, parts[2]); 
console.log(mydate.toDateString());

主要区别是,此处提供的第一个示例比第二个示例更简单,甚至更多的错误证明一个(至少在我看来,如下所述)。

因为如果您调用仅使用ISO格式的一个日期弦乐参数(第一个示例),它不接受高于其逻辑限制的值(因此,如果您给出13个月份或每天32个,则会获得无效的日期)。

但是,当您将同一构造函数与多个date-arguments(第二个示例)(第二个示例)时,逻辑限制将被调整为相邻值,并且您将不会得到无效的日期错误(因此,如果您给出13个月份,它将调整为1,而不是给予。您的日期无效)。

或替代方案(和第三)解决方案都可以混合在一起,使用第一个示例仅验证日期弦,如果它是有效的,请使用第二个示例(因此,您避免了可能的浏览器不一致,同时避免第二个示例的逻辑限制的参数许可)。

像这样(也接受部分日期):

function covertStringToDate(dateString) {
    //dateString should be in ISO format: "yyyy-mm-dd", "yyyy-mm" or "yyyy"
    if(new Date(dateString).toString() === "Invalid Date") {
        return false
    } else {
        const onlyNumbers = dateString.replace(/\D/g, ""); 
        const year = onlyNumbers.slice(0,4) 
        const month = onlyNumbers.slice(4,6)
        const day = onlyNumbers.slice(6,8)
        if(!month){
            return(new Date(year))
        } else if (!day) {
            return(new Date(year, month - 1))
        } else {
            return(new Date(year, month - 1, day))
        }        
    }
}

第四个替代方案(和最后的建议)将是使用适当的第三库(例如 date-fns

参考:

That's the best and simpler solution in my view:

Just concatenate your date string (using ISO format) with "T00:00:00" in the end and use the JavaScript Date() constructor, like the example below.

const dateString = '2014-04-03'
var mydate = new Date(dateString + "T00:00:00");
console.log(mydate.toDateString());

And just a few details about the solution above (but optional reading):

In ISO format, if you provide time and Z is not present in the end of
string, the date will be local time zone instead of UTC time
zone
. That means, when setting a date in this way, without
specifying the time zone, JavaScript will use the local browser's time
zone. And when getting a date, without specifying the time zone
as well, the result is also converted to the browser's time zone. And,
by default, almost every date method in JavaScript (except one)
gives you a date/time in local time zone as well (you only get UTC if
you specify UTC). So, using in local/browser time zone you probably
won't get unwanted results because difference between your
local/browse time zone and the UTC time zone, which is one of the main
complaints with date string conversion. But if you will use this
solution, understand your context and be aware of what you are doing.
And also be careful that omitting T or Z in a date-time string
can give different results in different browsers.

Important to note that the example above will give you exactly the same return to this example below, that is the second most voted answer in this question:

var parts ='2014-04-03'.split('-');
// Please pay attention to the month (parts[1]); JavaScript counts months from 0:
// January - 0, February - 1, etc.
var mydate = new Date(parts[0], parts[1] - 1, parts[2]); 
console.log(mydate.toDateString());

The main difference is that the first example provided here is simpler and even more error proof than the second one (at least in my view, as explained below).

Because if you call the JavaScript Date() constructor date with just one date-string argument in ISO format (first example), it doesn't accept values above its logical limit (so, if you give 13 as month or 32 as day, you get Invalid Date).

But when you use the same constructor with multiple date-arguments (second example), parameters above it logical limit will be adjusted to the adjacent value and you won't get Invalid Date Error (so, if you give 13 as month, it will adjust to 1, instead of give you an Invalid Date).

Or an alternative (and third) solution would be mix both, use the first example just to validate the date-string and if it is valid use the second example (so you avoid possible browsers inconsistences of the first example and at the same time avoid the permission of parameters above it logical limit of the second example).

Like so (accepting partial dates as well):

function covertStringToDate(dateString) {
    //dateString should be in ISO format: "yyyy-mm-dd", "yyyy-mm" or "yyyy"
    if(new Date(dateString).toString() === "Invalid Date") {
        return false
    } else {
        const onlyNumbers = dateString.replace(/\D/g, ""); 
        const year = onlyNumbers.slice(0,4) 
        const month = onlyNumbers.slice(4,6)
        const day = onlyNumbers.slice(6,8)
        if(!month){
            return(new Date(year))
        } else if (!day) {
            return(new Date(year, month - 1))
        } else {
            return(new Date(year, month - 1, day))
        }        
    }
}

And a fourth alternative (and last suggestion) would be to use an appropriate third library (like moment or date-fns)

References:

情痴 2025-01-26 14:23:33

如果您想从格式转换为“ DD/mm/yyyy”。这是一个示例:

var pattern = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/;
var arrayDate = stringDate.match(pattern);
var dt = new Date(arrayDate[3], arrayDate[2] - 1, arrayDate[1]);

此解决方案在IE版本中起作用,小于9。

If you want to convert from the format "dd/MM/yyyy". Here is an example:

var pattern = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/;
var arrayDate = stringDate.match(pattern);
var dt = new Date(arrayDate[3], arrayDate[2] - 1, arrayDate[1]);

This solution works in IE versions less than 9.

浮生未歇 2025-01-26 14:23:33

时间戳应该转换为数字

var ts = '1471793029764';
ts = Number(ts); // cast it to a Number
var date = new Date(ts); // works

var invalidDate = new Date('1471793029764'); // does not work. Invalid Date

Timestamps should be casted to a Number

var ts = '1471793029764';
ts = Number(ts); // cast it to a Number
var date = new Date(ts); // works

var invalidDate = new Date('1471793029764'); // does not work. Invalid Date
不弃不离 2025-01-26 14:23:33

date.parse 几乎可以为您带来想要的东西。它在 am / pm 零件上窒息,但是有些黑客可以使它起作用:

var str = 'Sun Apr 25, 2010 3:30pm',
    timestamp;

timestamp = Date.parse(str.replace(/[ap]m$/i, ''));

if(str.match(/pm$/i) >= 0) {
    timestamp += 12 * 60 * 60 * 1000;
}

Date.parse almost gets you what you want. It chokes on the am/pm part, but with some hacking you can get it to work:

var str = 'Sun Apr 25, 2010 3:30pm',
    timestamp;

timestamp = Date.parse(str.replace(/[ap]m$/i, ''));

if(str.match(/pm$/i) >= 0) {
    timestamp += 12 * 60 * 60 * 1000;
}
一抹苦笑 2025-01-26 14:23:33

今天的性能

(2020.05.08)我执行选择解决方案的测试 - 对于两种情况:输入日期为ISO8601字符串(AD,BD,CD,CD,DD,ED),并且输入日期为 timestamp (at,ct,dt)。 Solutions BD,CD,CT不返回JS日期对象作为结果,但我添加它们是因为它们可以有用,但我不将它们与有效解决方案进行比较。该结果对于大规模日期解析可能很有用。

结论

  • 解决方案新日期(AD)的速度比Moment.JS(DD)快50-100x,用于ISO日期和时间戳
  • 解决方案新日期(AD)为〜10X比 parsedate (ed)
  • 解决方案 date.parse.parse (bd)更快,如果WEE需要从所有浏览器上从ISO日期获得时间戳

“ rel =“ noreferrer

i.sstatic.net/yjdwq.png 在Chrome 81.0,Safari 13.1,Firefox 75.0上对MacOS高塞拉10.13.6进行测试。解决方案 parsedate (ed)使用 new Date(0)并手动设置UTC日期组件。

let ds = '2020-05-14T00:00Z'; // Valid ISO8601 UTC date
let ts = +'1589328000000';    // timestamp

let Ad = new Date(ds);
let Bd = Date.parse(ds);
let Cd = moment(ds);
let Dd = moment(ds).toDate();
let Ed = parseDate(ds);

let At = new Date(ts);
let Ct = moment(ts);
let Dt = moment(ts).toDate();

log = (n,d) => console.log(`${n}: ${+d} ${d}`);

console.log('from date string:', ds)
log('Ad', Ad);
log('Bd', Bd);
log('Cd', Cd);
log('Dd', Dd);
log('Ed', Ed);
console.log('from timestamp:', ts)
log('At', At);
log('Ct', Ct);
log('Dt', Dt);



function parseDate(dateStr) {
  let [year,month,day] = dateStr.split(' ')[0].split('-');
  let d=new Date(0);
  d.setUTCFullYear(year);
  d.setUTCMonth(month-1);
  d.setUTCDate(day)
  return d;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.1/moment-with-locales.min.js"></script>

This snippet only presents used soultions  

Chrome

Performance

Today (2020.05.08) I perform tests for chosen solutions - for two cases: input date is ISO8601 string (Ad,Bd,Cd,Dd,Ed) and input date is timestamp (At, Ct, Dt). Solutions Bd,Cd,Ct not return js Date object as results, but I add them because they can be useful but I not compare them with valid solutions. This results can be useful for massive date parsing.

Conclusions

  • Solution new Date (Ad) is 50-100x faster than moment.js (Dd) for all browsers for ISO date and timestamp
  • Solution new Date (Ad) is ~10x faster than parseDate (Ed)
  • Solution Date.parse(Bd) is fastest if wee need to get timestamp from ISO date on all browsers

enter image description here

Details

I perform test on MacOs High Sierra 10.13.6 on Chrome 81.0, Safari 13.1, Firefox 75.0. Solution parseDate (Ed) use new Date(0) and manually set UTC date components.

let ds = '2020-05-14T00:00Z'; // Valid ISO8601 UTC date
let ts = +'1589328000000';    // timestamp

let Ad = new Date(ds);
let Bd = Date.parse(ds);
let Cd = moment(ds);
let Dd = moment(ds).toDate();
let Ed = parseDate(ds);

let At = new Date(ts);
let Ct = moment(ts);
let Dt = moment(ts).toDate();

log = (n,d) => console.log(`${n}: ${+d} ${d}`);

console.log('from date string:', ds)
log('Ad', Ad);
log('Bd', Bd);
log('Cd', Cd);
log('Dd', Dd);
log('Ed', Ed);
console.log('from timestamp:', ts)
log('At', At);
log('Ct', Ct);
log('Dt', Dt);



function parseDate(dateStr) {
  let [year,month,day] = dateStr.split(' ')[0].split('-');
  let d=new Date(0);
  d.setUTCFullYear(year);
  d.setUTCMonth(month-1);
  d.setUTCDate(day)
  return d;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.1/moment-with-locales.min.js"></script>

This snippet only presents used soultions  

Results for chrome

enter image description here

长梦不多时 2025-01-26 14:23:33

转换为格式pt-br:

    var dateString = "13/10/2014";
    var dataSplit = dateString.split('/');
    var dateConverted;

    if (dataSplit[2].split(" ").length > 1) {

        var hora = dataSplit[2].split(" ")[1].split(':');
        dataSplit[2] = dataSplit[2].split(" ")[0];
        dateConverted = new Date(dataSplit[2], dataSplit[1]-1, dataSplit[0], hora[0], hora[1]);

    } else {
        dateConverted = new Date(dataSplit[2], dataSplit[1] - 1, dataSplit[0]);
    }

我希望帮助某人!!!

Convert to format pt-BR:

    var dateString = "13/10/2014";
    var dataSplit = dateString.split('/');
    var dateConverted;

    if (dataSplit[2].split(" ").length > 1) {

        var hora = dataSplit[2].split(" ")[1].split(':');
        dataSplit[2] = dataSplit[2].split(" ")[0];
        dateConverted = new Date(dataSplit[2], dataSplit[1]-1, dataSplit[0], hora[0], hora[1]);

    } else {
        dateConverted = new Date(dataSplit[2], dataSplit[1] - 1, dataSplit[0]);
    }

I hope help somebody!!!

浊酒尽余欢 2025-01-26 14:23:33

我为此创建了一个小提琴,您可以在任何日期字符串上使用 toDate() 函数并提供日期格式。这将返回一个 Date 对象。
https://jsfiddle.net/Sus​​hil231088/q56yd0rp/

"17/9/2014".toDate("dd/MM/yyyy", "/")

I have created a fiddle for this, you can use toDate() function on any date string and provide the date format. This will return you a Date object.
https://jsfiddle.net/Sushil231088/q56yd0rp/

"17/9/2014".toDate("dd/MM/yyyy", "/")
蓝眼泪 2025-01-26 14:23:33

对于js中的converting字符串,我使用 http://momentjs.com/

moment().format('MMMM Do YYYY, h:mm:ss a'); // August 16th 2015, 4:17:24 pm
moment().format('dddd');                    // Sunday
moment().format("MMM Do YY");               // Aug 16th 15
moment().format('YYYY [escaped] YYYY');     // 2015 escaped 2015
moment("20111031", "YYYYMMDD").fromNow(); // 4 years ago
moment("20120620", "YYYYMMDD").fromNow(); // 3 years ago
moment().startOf('day').fromNow();        // 16 hours ago
moment().endOf('day').fromNow();          // in 8 hours

For сonverting string to date in js i use http://momentjs.com/

moment().format('MMMM Do YYYY, h:mm:ss a'); // August 16th 2015, 4:17:24 pm
moment().format('dddd');                    // Sunday
moment().format("MMM Do YY");               // Aug 16th 15
moment().format('YYYY [escaped] YYYY');     // 2015 escaped 2015
moment("20111031", "YYYYMMDD").fromNow(); // 4 years ago
moment("20120620", "YYYYMMDD").fromNow(); // 3 years ago
moment().startOf('day').fromNow();        // 16 hours ago
moment().endOf('day').fromNow();          // in 8 hours
独留℉清风醉 2025-01-26 14:23:33

我使此功能将任何日期对象转换为UTC日期对象。

function dateToUTC(date) {
    return new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
}


dateToUTC(new Date());

I made this function to convert any Date object to a UTC Date object.

function dateToUTC(date) {
    return new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
}


dateToUTC(new Date());
岁月静好 2025-01-26 14:23:33

您可以使用正则表达式解析字符串以详细说明时间,然后创建日期或任何返回格式,例如:

//example : let dateString = "2018-08-17 01:02:03.4"

function strToDate(dateString){
    let reggie = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2}).(\d{1})/
  , [,year, month, day, hours, minutes, seconds, miliseconds] = reggie.exec(dateString)
  , dateObject = new Date(year, month-1, day, hours, minutes, seconds, miliseconds);
  return dateObject;
}
alert(strToDate(dateString));

You can using regex to parse string to detail time then create date or any return format like :

//example : let dateString = "2018-08-17 01:02:03.4"

function strToDate(dateString){
    let reggie = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2}).(\d{1})/
  , [,year, month, day, hours, minutes, seconds, miliseconds] = reggie.exec(dateString)
  , dateObject = new Date(year, month-1, day, hours, minutes, seconds, miliseconds);
  return dateObject;
}
alert(strToDate(dateString));
诗酒趁年少 2025-01-26 14:23:33

您可以尝试一下:

function formatDate(userDOB) {
  const dob = new Date(userDOB);

  const monthNames = [
    'January', 'February', 'March', 'April', 'May', 'June', 'July',
     'August', 'September', 'October', 'November', 'December'
  ];

  const day = dob.getDate();
  const monthIndex = dob.getMonth();
  const year = dob.getFullYear();

  // return day + ' ' + monthNames[monthIndex] + ' ' + year;
  return `${day} ${monthNames[monthIndex]} ${year}`;
}

console.log(formatDate('1982-08-10'));

You Can try this:

function formatDate(userDOB) {
  const dob = new Date(userDOB);

  const monthNames = [
    'January', 'February', 'March', 'April', 'May', 'June', 'July',
     'August', 'September', 'October', 'November', 'December'
  ];

  const day = dob.getDate();
  const monthIndex = dob.getMonth();
  const year = dob.getFullYear();

  // return day + ' ' + monthNames[monthIndex] + ' ' + year;
  return `${day} ${monthNames[monthIndex]} ${year}`;
}

console.log(formatDate('1982-08-10'));

挽容 2025-01-26 14:23:33

这个答案基于 Kassem 的答案,但它也处理两位数的年份。我提交了对卡西姆答案的编辑,但如果未获得批准,我也会将其作为单独的答案提交。

function stringToDate(_date,_format,_delimiter) {
        var formatLowerCase=_format.toLowerCase();
        var formatItems=formatLowerCase.split(_delimiter);
        var dateItems=_date.split(_delimiter);
        var monthIndex=formatItems.indexOf("mm");
        var dayIndex=formatItems.indexOf("dd");
        var yearIndex=formatItems.indexOf("yyyy");
        var year = parseInt(dateItems[yearIndex]); 
        // adjust for 2 digit year
        if (year < 100) { year += 2000; }
        var month=parseInt(dateItems[monthIndex]);
        month-=1;
        var formatedDate = new Date(year,month,dateItems[dayIndex]);
        return formatedDate;
}

stringToDate("17/9/14","dd/MM/yyyy","/");
stringToDate("17/9/2014","dd/MM/yyyy","/");
stringToDate("9/17/2014","mm/dd/yyyy","/")
stringToDate("9-17-2014","mm-dd-yyyy","-")

This answer is based on Kassem's answer but it also handles two-digit years. I submitted an edit to Kassem's answer, but in case it wasn't approved, I'm also submitting this as a separate answer.

function stringToDate(_date,_format,_delimiter) {
        var formatLowerCase=_format.toLowerCase();
        var formatItems=formatLowerCase.split(_delimiter);
        var dateItems=_date.split(_delimiter);
        var monthIndex=formatItems.indexOf("mm");
        var dayIndex=formatItems.indexOf("dd");
        var yearIndex=formatItems.indexOf("yyyy");
        var year = parseInt(dateItems[yearIndex]); 
        // adjust for 2 digit year
        if (year < 100) { year += 2000; }
        var month=parseInt(dateItems[monthIndex]);
        month-=1;
        var formatedDate = new Date(year,month,dateItems[dayIndex]);
        return formatedDate;
}

stringToDate("17/9/14","dd/MM/yyyy","/");
stringToDate("17/9/2014","dd/MM/yyyy","/");
stringToDate("9/17/2014","mm/dd/yyyy","/")
stringToDate("9-17-2014","mm-dd-yyyy","-")
人疚 2025-01-26 14:23:33
var date = new Date(year, month, day);

或者

var date = new Date('01/01/1970');

“01-01-1970”格式的日期字符串在 FireFox 中不起作用,因此最好在日期格式字符串中使用“/”而不是“-”。

var date = new Date(year, month, day);

or

var date = new Date('01/01/1970');

date string in format '01-01-1970' will not work in FireFox, So better use "/" instead of "-" in date format string.

寄居者 2025-01-26 14:23:33

还有另一种方法可以做到这一点:

String.prototype.toDate = function(format) {
    format = format || "dmy";
    var separator = this.match(/[^0-9]/)[0];
    var components = this.split(separator);
    var day, month, year;
    for (var key in format) {
        var fmt_value = format[key];
        var value = components[key];
        switch (fmt_value) {
            case "d":
                day = parseInt(value);
                break;
            case "m":
                month = parseInt(value)-1;
                break;
            case "y":
                year = parseInt(value);
        }
    }
    return new Date(year, month, day);
};
a = "3/2/2017";
console.log(a.toDate("dmy"));
// Date 2017-02-03T00:00:00.000Z

Yet another way to do it:

String.prototype.toDate = function(format) {
    format = format || "dmy";
    var separator = this.match(/[^0-9]/)[0];
    var components = this.split(separator);
    var day, month, year;
    for (var key in format) {
        var fmt_value = format[key];
        var value = components[key];
        switch (fmt_value) {
            case "d":
                day = parseInt(value);
                break;
            case "m":
                month = parseInt(value)-1;
                break;
            case "y":
                year = parseInt(value);
        }
    }
    return new Date(year, month, day);
};
a = "3/2/2017";
console.log(a.toDate("dmy"));
// Date 2017-02-03T00:00:00.000Z
一袭白衣梦中忆 2025-01-26 14:23:33

如果您需要在转换为日期格式之前检查字符串的内容:

// Convert 'M/D/YY' to Date()
mdyToDate = function(mdy) {
  var d = mdy.split(/[\/\-\.]/, 3);

  if (d.length != 3) return null;

  // Check if date is valid
  var mon = parseInt(d[0]), 
      day = parseInt(d[1]),
      year= parseInt(d[2]);
  if (d[2].length == 2) year += 2000;
  if (day <= 31 && mon <= 12 && year >= 2015)
    return new Date(year, mon - 1, day);

  return null; 
}

If you need to check the contents of the string before converting to Date format:

// Convert 'M/D/YY' to Date()
mdyToDate = function(mdy) {
  var d = mdy.split(/[\/\-\.]/, 3);

  if (d.length != 3) return null;

  // Check if date is valid
  var mon = parseInt(d[0]), 
      day = parseInt(d[1]),
      year= parseInt(d[2]);
  if (d[2].length == 2) year += 2000;
  if (day <= 31 && mon <= 12 && year >= 2015)
    return new Date(year, mon - 1, day);

  return null; 
}
旧伤慢歌 2025-01-26 14:23:33

我已经创建了ParseDateTime函数以将字符串转换为日期对象,并且它在所有浏览器(包括IE浏览器)中工作,检查是否需要,参考
https://github.com/umesh-markande/解析 - 弦乐到日期 - 全螺旋体

    function parseDateTime(datetime) {
            var monthNames = [
                "January", "February", "March",
                "April", "May", "June", "July",
                "August", "September", "October",
                "November", "December"
              ];
            if(datetime.split(' ').length == 3){
                var date = datetime.split(' ')[0];
                var time = datetime.split(' ')[1].replace('.00','');
                var timearray = time.split(':');
                var hours = parseInt(time.split(':')[0]);
                var format = datetime.split(' ')[2];
                var bits = date.split(/\D/);
                date = new Date(bits[0], --bits[1], bits[2]); /* if you change format of datetime which is passed to this function, you need to change bits e.x ( bits[0], bits[1], bits[2 ]) position as per date, months and year it represent bits array.*/
                var day = date.getDate();
                var monthIndex = date.getMonth();
                var year = date.getFullYear();
                if ((format === 'PM' || format === 'pm') && hours !== 12) {
                    hours += 12;
                    try{  time = hours+':'+timearray[1]+':'+timearray[2] }catch(e){ time = hours+':'+timearray[1] }
                } 
                var formateddatetime = new Date(monthNames[monthIndex] + ' ' + day + '  ' + year + ' ' + time);
                return formateddatetime;
            }else if(datetime.split(' ').length == 2){
                var date = datetime.split(' ')[0];
                var time = datetime.split(' ')[1];
                var bits = date.split(/\D/);
                var datetimevalue = new Date(bits[0], --bits[1], bits[2]); /* if you change format of datetime which is passed to this function, you need to change bits e.x ( bits[0], bits[1], bits[2 ]) position as per date, months and year it represent bits array.*/
                var day = datetimevalue.getDate();
                var monthIndex = datetimevalue.getMonth();
                var year = datetimevalue.getFullYear();
                var formateddatetime = new Date(monthNames[monthIndex] + ' ' + day + '  ' + year + ' ' + time);
                return formateddatetime;
            }else if(datetime != ''){
                var bits = datetime.split(/\D/);
                var date = new Date(bits[0], --bits[1], bits[2]); /* if you change format of datetime which is passed to this function, you need to change bits e.x ( bits[0], bits[1], bits[2 ]) position as per date, months and year it represent bits array.*/
                return date;
            }
            return datetime;
        }

    var date1 = '2018-05-14 05:04:22 AM';   // yyyy-mm-dd hh:mm:ss A
    var date2 = '2018/05/14 05:04:22 AM';   // yyyy/mm/dd hh:mm:ss A
    var date3 = '2018/05/04';   // yyyy/mm/dd
    var date4 = '2018-05-04';   // yyyy-mm-dd
    var date5 = '2018-05-14 15:04:22';   // yyyy-mm-dd HH:mm:ss
    var date6 = '2018/05/14 14:04:22';   // yyyy/mm/dd HH:mm:ss

    console.log(parseDateTime(date1))
    console.log(parseDateTime(date2))
    console.log(parseDateTime(date3))
    console.log(parseDateTime(date4))
    console.log(parseDateTime(date5))
    console.log(parseDateTime(date6))

**Output---**
Mon May 14 2018 05:04:22 GMT+0530 (India Standard Time)
Mon May 14 2018 05:04:22 GMT+0530 (India Standard Time)
Fri May 04 2018 00:00:00 GMT+0530 (India Standard Time)
Fri May 04 2018 00:00:00 GMT+0530 (India Standard Time)
Mon May 14 2018 15:04:22 GMT+0530 (India Standard Time)
Mon May 14 2018 14:04:22 GMT+0530 (India Standard Time)

I have created parseDateTime function to convert the string to date object and it is working in all browser (including IE browser), check if anyone required, reference
https://github.com/Umesh-Markande/Parse-String-to-Date-in-all-browser

    function parseDateTime(datetime) {
            var monthNames = [
                "January", "February", "March",
                "April", "May", "June", "July",
                "August", "September", "October",
                "November", "December"
              ];
            if(datetime.split(' ').length == 3){
                var date = datetime.split(' ')[0];
                var time = datetime.split(' ')[1].replace('.00','');
                var timearray = time.split(':');
                var hours = parseInt(time.split(':')[0]);
                var format = datetime.split(' ')[2];
                var bits = date.split(/\D/);
                date = new Date(bits[0], --bits[1], bits[2]); /* if you change format of datetime which is passed to this function, you need to change bits e.x ( bits[0], bits[1], bits[2 ]) position as per date, months and year it represent bits array.*/
                var day = date.getDate();
                var monthIndex = date.getMonth();
                var year = date.getFullYear();
                if ((format === 'PM' || format === 'pm') && hours !== 12) {
                    hours += 12;
                    try{  time = hours+':'+timearray[1]+':'+timearray[2] }catch(e){ time = hours+':'+timearray[1] }
                } 
                var formateddatetime = new Date(monthNames[monthIndex] + ' ' + day + '  ' + year + ' ' + time);
                return formateddatetime;
            }else if(datetime.split(' ').length == 2){
                var date = datetime.split(' ')[0];
                var time = datetime.split(' ')[1];
                var bits = date.split(/\D/);
                var datetimevalue = new Date(bits[0], --bits[1], bits[2]); /* if you change format of datetime which is passed to this function, you need to change bits e.x ( bits[0], bits[1], bits[2 ]) position as per date, months and year it represent bits array.*/
                var day = datetimevalue.getDate();
                var monthIndex = datetimevalue.getMonth();
                var year = datetimevalue.getFullYear();
                var formateddatetime = new Date(monthNames[monthIndex] + ' ' + day + '  ' + year + ' ' + time);
                return formateddatetime;
            }else if(datetime != ''){
                var bits = datetime.split(/\D/);
                var date = new Date(bits[0], --bits[1], bits[2]); /* if you change format of datetime which is passed to this function, you need to change bits e.x ( bits[0], bits[1], bits[2 ]) position as per date, months and year it represent bits array.*/
                return date;
            }
            return datetime;
        }

    var date1 = '2018-05-14 05:04:22 AM';   // yyyy-mm-dd hh:mm:ss A
    var date2 = '2018/05/14 05:04:22 AM';   // yyyy/mm/dd hh:mm:ss A
    var date3 = '2018/05/04';   // yyyy/mm/dd
    var date4 = '2018-05-04';   // yyyy-mm-dd
    var date5 = '2018-05-14 15:04:22';   // yyyy-mm-dd HH:mm:ss
    var date6 = '2018/05/14 14:04:22';   // yyyy/mm/dd HH:mm:ss

    console.log(parseDateTime(date1))
    console.log(parseDateTime(date2))
    console.log(parseDateTime(date3))
    console.log(parseDateTime(date4))
    console.log(parseDateTime(date5))
    console.log(parseDateTime(date6))

**Output---**
Mon May 14 2018 05:04:22 GMT+0530 (India Standard Time)
Mon May 14 2018 05:04:22 GMT+0530 (India Standard Time)
Fri May 04 2018 00:00:00 GMT+0530 (India Standard Time)
Fri May 04 2018 00:00:00 GMT+0530 (India Standard Time)
Mon May 14 2018 15:04:22 GMT+0530 (India Standard Time)
Mon May 14 2018 14:04:22 GMT+0530 (India Standard Time)
浪荡不羁 2025-01-26 14:23:33

ISO 8601 式的日期字符串虽然非常优秀,但仍未得到广泛支持。

这是一个很好的资源,可以帮助您确定应该使用哪种日期字符串格式:

http://dygraphs.com/date- format.html

是的,这意味着您的日期字符串可以像

"2014/10/13 23:57:52" 一样简单
而不是
“2014-10-13 23:57:52”

ISO 8601-esque datestrings, as excellent as the standard is, are still not widely supported.

This is a great resource to figure out which datestring format you should use:

http://dygraphs.com/date-formats.html

Yes, that means that your datestring could be as simple as as opposed to

"2014/10/13 23:57:52"
instead of
"2014-10-13 23:57:52"

路还长,别太狂 2025-01-26 14:23:33

作为此处解释的内容的插件,您可以使用 new Date()创建日期,并使用非常有用的toLocaleDateString() function

An example:

console.log(new Date('1970-01- 01')。tolocaledateString('es-es'))// - &gt;这将输出'1/1/1970'

As an addon to what has been explained here, you can create your Date with new Date() and format it with the incredibly useful toLocaleDateString() function

An example:

console.log(new Date('1970-01-01').toLocaleDateString('es-ES')) // --> This will output '1/1/1970'

围归者 2025-01-26 14:23:33
                //little bit of code for Converting dates 

                var dat1 = document.getElementById('inputDate').value;
                var date1 = new Date(dat1)//converts string to date object
                alert(date1);
                var dat2 = document.getElementById('inputFinishDate').value;
                var date2 = new Date(dat2)
                alert(date2);
                //little bit of code for Converting dates 

                var dat1 = document.getElementById('inputDate').value;
                var date1 = new Date(dat1)//converts string to date object
                alert(date1);
                var dat2 = document.getElementById('inputFinishDate').value;
                var date2 = new Date(dat2)
                alert(date2);
思慕 2025-01-26 14:23:33

使用这段代码:(我的问题已经用这段代码解决了)

function dateDiff(date1, date2){
var diff = {}                           // Initialisation du retour
var tmp = date2 - date1;

tmp = Math.floor(tmp/1000);             // Nombre de secondes entre les 2 dates
diff.sec = tmp % 60;                    // Extraction du nombre de secondes

tmp = Math.floor((tmp-diff.sec)/60);    // Nombre de minutes (partie entière)
diff.min = tmp % 60;                    // Extraction du nombre de minutes

tmp = Math.floor((tmp-diff.min)/60);    // Nombre d'heures (entières)
diff.hour = tmp % 24;                   // Extraction du nombre d'heures

tmp = Math.floor((tmp-diff.hour)/24);   // Nombre de jours restants
diff.day = tmp;

return diff;

}

use this code : (my problem was solved with this code)

function dateDiff(date1, date2){
var diff = {}                           // Initialisation du retour
var tmp = date2 - date1;

tmp = Math.floor(tmp/1000);             // Nombre de secondes entre les 2 dates
diff.sec = tmp % 60;                    // Extraction du nombre de secondes

tmp = Math.floor((tmp-diff.sec)/60);    // Nombre de minutes (partie entière)
diff.min = tmp % 60;                    // Extraction du nombre de minutes

tmp = Math.floor((tmp-diff.min)/60);    // Nombre d'heures (entières)
diff.hour = tmp % 24;                   // Extraction du nombre d'heures

tmp = Math.floor((tmp-diff.hour)/24);   // Nombre de jours restants
diff.day = tmp;

return diff;

}

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文