如何使用JavaScript中的格式规范将字符串转换为datetime ?

时间:2022-04-11 15:54:03

How can I convert a string to a date time object in javascript by specifying a format string?

如何通过指定格式字符串将字符串转换为javascript中的日期时间对象?

I am looking for something like:

我想找的是:

var dateTime = convertToDateTime("23.11.2009 12:34:56", "dd.MM.yyyy HH:mm:ss");

13 个解决方案

#1


88  

I think this can help you: http://www.mattkruse.com/javascript/date/

我认为这可以帮助您:http://www.mattkruse.com/javascript/date/

There's a getDateFromFormat() function that you can tweak a little to solve your problem.

有一个getDateFromFormat()函数,您可以稍作调整以解决您的问题。

Update: there's an updated version of the samples available at javascripttoolbox.com

更新:在javascripttoolbox.com上有一个更新版本的样本。

#2


82  

Use new Date(dateString) if your string is compatible with Date.parse(). If your format is incompatible (I think it is), you have to parse the string yourself (should be easy with regular expressions) and create a new Date object with explicit values for year, month, date, hour, minute and second.

如果您的字符串与data .parse()兼容,则使用new Date(dateString)。如果您的格式不兼容(我认为是不兼容的),您必须自己解析字符串(使用正则表达式应该很容易),并为年、月、日期、小时、分钟和秒创建一个具有显式值的新日期对象。

#3


56  

@Christoph Mentions using a regex to tackle the problem. Here's what I'm using:

@Christoph提到使用regex来解决这个问题。这就是我使用:

var dateString = "2010-08-09 01:02:03";
var reggie = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/;
var dateArray = reggie.exec(dateString); 
var dateObject = new Date(
    (+dateArray[1]),
    (+dateArray[2])-1, // Careful, month starts at 0!
    (+dateArray[3]),
    (+dateArray[4]),
    (+dateArray[5]),
    (+dateArray[6])
);

It's by no means intelligent, just configure the regex and new Date(blah) to suit your needs.

它一点也不聪明,只需配置regex和new Date(等等)以满足您的需求。

Edit: Maybe a bit more understandable in ES6 using destructuring:

编辑:也许在ES6中使用析构更容易理解一些:

let dateString = "2010-08-09 01:02:03"
  , reggie = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/
  , [, year, month, day, hours, minutes, seconds] = reggie.exec(dateString)
  , dateObject = new Date(year, month-1, day, hours, minutes, seconds);

But in all honesty these days I reach for something like Moment

但说实话,这些天来,我想要的是类似的时刻

#4


14  

No sophisticated date/time formatting routines exist in JavaScript.

JavaScript中不存在复杂的日期/时间格式例程。

You will have to use an external library for formatted date output, "JavaScript Date Format" from Flagrant Badassery looks very promising.

您将不得不使用一个外部库来进行格式化的日期输出,恶意的Badassery提供的“JavaScript日期格式”看起来很有希望。

For the input conversion, several suggestions have been made already. :)

对于输入转换,已经提出了几点建议。:)

#5


13  

Check out Moment.js. It is a modern and powerful library that makes up for JavaScript's woeful Date functions (or lack thereof).

查看Moment.js。它是一个现代而强大的库,可以弥补JavaScript糟糕的日期函数(或缺少的)。

#6


11  

Just for an updated answer here, there's a good js lib at http://www.datejs.com/

这里有一个更新的答案,http://www.datejs.com/有一个很好的js lib

#7


7  

var temp1 = "";
var temp2 = "";

var str1 = fd; 
var str2 = td;

var dt1  = str1.substring(0,2);
var dt2  = str2.substring(0,2);

var mon1 = str1.substring(3,5);
var mon2 = str2.substring(3,5);

var yr1  = str1.substring(6,10);  
var yr2  = str2.substring(6,10); 

temp1 = mon1 + "/" + dt1 + "/" + yr1;
temp2 = mon2 + "/" + dt2 + "/" + yr2;

var cfd = Date.parse(temp1);
var ctd = Date.parse(temp2);

var date1 = new Date(cfd); 
var date2 = new Date(ctd);

if(date1 > date2) { 
    alert("FROM DATE SHOULD BE MORE THAN TO DATE");
}

#8


4  

External library is an overkill for parsing one or two dates, so I made my own function using Oli's and Christoph's solutions. Here in central Europe we rarely use aything but the OP's format, so this should be enough for simple apps used here.

对于解析一两个日期来说,外部库是多余的,因此我使用Oli和Christoph的解决方案创建了自己的函数。在中欧,除了OP的格式,我们很少使用aything,因此对于这里使用的简单应用来说,这应该足够了。

function ParseDate(dateString) {
    //dd.mm.yyyy, or dd.mm.yy
    var dateArr = dateString.split(".");
    if (dateArr.length == 1) {
        return null;    //wrong format
    }
    //parse time after the year - separated by space
    var spacePos = dateArr[2].indexOf(" ");
    if(spacePos > 1) {
        var timeString = dateArr[2].substr(spacePos + 1);
        var timeArr = timeString.split(":");
        dateArr[2] = dateArr[2].substr(0, spacePos);
        if (timeArr.length == 2) {
            //minutes only
            return new Date(parseInt(dateArr[2]), parseInt(dateArr[1]-1), parseInt(dateArr[0]), parseInt(timeArr[0]), parseInt(timeArr[1]));
        } else {
            //including seconds
            return new Date(parseInt(dateArr[2]), parseInt(dateArr[1]-1), parseInt(dateArr[0]), parseInt(timeArr[0]), parseInt(timeArr[1]), parseInt(timeArr[2]))
        }
    } else {
        //gotcha at months - January is at 0, not 1 as one would expect
        return new Date(parseInt(dateArr[2]), parseInt(dateArr[1] - 1), parseInt(dateArr[0]));
    }
}

#9


3  

Date.parse() is fairly intelligent but I can't guarantee that format will parse correctly.

parser()是相当智能的,但是我不能保证格式能够正确地解析。

If it doesn't, you'd have to find something to bridge the two. Your example is pretty simple (being purely numbers) so a touch of REGEX (or even string.split() -- might be faster) paired with some parseInt() will allow you to quickly make a date.

如果没有的话,你就得找些东西把这两者连接起来。您的示例非常简单(纯粹是数字),所以使用REGEX(甚至string.split()——可能会更快)与parseInt()配合将使您能够快速确定日期。

#10


2  

Just to give my 5 cents.

给我5美分。

My date format is dd.mm.yyyy (UK format) and none of the above examples were working for me. All the parsers were considering mm as day and dd as month.

我的日期格式是。yyyyy(英国格式)和上面的例子没有一个对我有效。所有的解析器都将mm视为day, dd视为month。

I've found this library: http://joey.mazzarelli.com/2008/11/25/easy-date-parsing-with-javascript/ and it worked, because you can say the order of the fields like this:

我找到了这个库:http://joey.mazzarelli.com/2008/11/25/date-par- javascript/,它起作用了,因为您可以这样说字段的顺序:

>>console.log(new Date(Date.fromString('09.05.2012', {order: 'DMY'})));
Wed May 09 2012 00:00:00 GMT+0300 (EEST)

I hope that helps someone.

我希望能帮助别人。

#11


1  

Moment.js will handle this:

的时刻。js将处理这个问题:

var momentDate = moment('23.11.2009 12:34:56', 'DD.MM.YYYY HH:mm:ss');
var date = momentDate.;

#12


0  

To fully satisfy the Date.parse convert string to format dd-mm-YYYY as specified in RFC822, if you use yyyy-mm-dd parse may do a mistakes.

完全满足日期。在RFC822中,如果使用yyyy-mm-dd解析可能会出错,那么解析转换字符串的格式为dd-mm-YYYY。

#13


0  

time = "2017-01-18T17:02:09.000+05:30"

t = new Date(time)

hr = ("0" + t.getHours()).slice(-2);
min = ("0" + t.getMinutes()).slice(-2);
sec = ("0" + t.getSeconds()).slice(-2);

t.getFullYear()+"-"+t.getMonth()+1+"-"+t.getDate()+" "+hr+":"+min+":"+sec

#1


88  

I think this can help you: http://www.mattkruse.com/javascript/date/

我认为这可以帮助您:http://www.mattkruse.com/javascript/date/

There's a getDateFromFormat() function that you can tweak a little to solve your problem.

有一个getDateFromFormat()函数,您可以稍作调整以解决您的问题。

Update: there's an updated version of the samples available at javascripttoolbox.com

更新:在javascripttoolbox.com上有一个更新版本的样本。

#2


82  

Use new Date(dateString) if your string is compatible with Date.parse(). If your format is incompatible (I think it is), you have to parse the string yourself (should be easy with regular expressions) and create a new Date object with explicit values for year, month, date, hour, minute and second.

如果您的字符串与data .parse()兼容,则使用new Date(dateString)。如果您的格式不兼容(我认为是不兼容的),您必须自己解析字符串(使用正则表达式应该很容易),并为年、月、日期、小时、分钟和秒创建一个具有显式值的新日期对象。

#3


56  

@Christoph Mentions using a regex to tackle the problem. Here's what I'm using:

@Christoph提到使用regex来解决这个问题。这就是我使用:

var dateString = "2010-08-09 01:02:03";
var reggie = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/;
var dateArray = reggie.exec(dateString); 
var dateObject = new Date(
    (+dateArray[1]),
    (+dateArray[2])-1, // Careful, month starts at 0!
    (+dateArray[3]),
    (+dateArray[4]),
    (+dateArray[5]),
    (+dateArray[6])
);

It's by no means intelligent, just configure the regex and new Date(blah) to suit your needs.

它一点也不聪明,只需配置regex和new Date(等等)以满足您的需求。

Edit: Maybe a bit more understandable in ES6 using destructuring:

编辑:也许在ES6中使用析构更容易理解一些:

let dateString = "2010-08-09 01:02:03"
  , reggie = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/
  , [, year, month, day, hours, minutes, seconds] = reggie.exec(dateString)
  , dateObject = new Date(year, month-1, day, hours, minutes, seconds);

But in all honesty these days I reach for something like Moment

但说实话,这些天来,我想要的是类似的时刻

#4


14  

No sophisticated date/time formatting routines exist in JavaScript.

JavaScript中不存在复杂的日期/时间格式例程。

You will have to use an external library for formatted date output, "JavaScript Date Format" from Flagrant Badassery looks very promising.

您将不得不使用一个外部库来进行格式化的日期输出,恶意的Badassery提供的“JavaScript日期格式”看起来很有希望。

For the input conversion, several suggestions have been made already. :)

对于输入转换,已经提出了几点建议。:)

#5


13  

Check out Moment.js. It is a modern and powerful library that makes up for JavaScript's woeful Date functions (or lack thereof).

查看Moment.js。它是一个现代而强大的库,可以弥补JavaScript糟糕的日期函数(或缺少的)。

#6


11  

Just for an updated answer here, there's a good js lib at http://www.datejs.com/

这里有一个更新的答案,http://www.datejs.com/有一个很好的js lib

#7


7  

var temp1 = "";
var temp2 = "";

var str1 = fd; 
var str2 = td;

var dt1  = str1.substring(0,2);
var dt2  = str2.substring(0,2);

var mon1 = str1.substring(3,5);
var mon2 = str2.substring(3,5);

var yr1  = str1.substring(6,10);  
var yr2  = str2.substring(6,10); 

temp1 = mon1 + "/" + dt1 + "/" + yr1;
temp2 = mon2 + "/" + dt2 + "/" + yr2;

var cfd = Date.parse(temp1);
var ctd = Date.parse(temp2);

var date1 = new Date(cfd); 
var date2 = new Date(ctd);

if(date1 > date2) { 
    alert("FROM DATE SHOULD BE MORE THAN TO DATE");
}

#8


4  

External library is an overkill for parsing one or two dates, so I made my own function using Oli's and Christoph's solutions. Here in central Europe we rarely use aything but the OP's format, so this should be enough for simple apps used here.

对于解析一两个日期来说,外部库是多余的,因此我使用Oli和Christoph的解决方案创建了自己的函数。在中欧,除了OP的格式,我们很少使用aything,因此对于这里使用的简单应用来说,这应该足够了。

function ParseDate(dateString) {
    //dd.mm.yyyy, or dd.mm.yy
    var dateArr = dateString.split(".");
    if (dateArr.length == 1) {
        return null;    //wrong format
    }
    //parse time after the year - separated by space
    var spacePos = dateArr[2].indexOf(" ");
    if(spacePos > 1) {
        var timeString = dateArr[2].substr(spacePos + 1);
        var timeArr = timeString.split(":");
        dateArr[2] = dateArr[2].substr(0, spacePos);
        if (timeArr.length == 2) {
            //minutes only
            return new Date(parseInt(dateArr[2]), parseInt(dateArr[1]-1), parseInt(dateArr[0]), parseInt(timeArr[0]), parseInt(timeArr[1]));
        } else {
            //including seconds
            return new Date(parseInt(dateArr[2]), parseInt(dateArr[1]-1), parseInt(dateArr[0]), parseInt(timeArr[0]), parseInt(timeArr[1]), parseInt(timeArr[2]))
        }
    } else {
        //gotcha at months - January is at 0, not 1 as one would expect
        return new Date(parseInt(dateArr[2]), parseInt(dateArr[1] - 1), parseInt(dateArr[0]));
    }
}

#9


3  

Date.parse() is fairly intelligent but I can't guarantee that format will parse correctly.

parser()是相当智能的,但是我不能保证格式能够正确地解析。

If it doesn't, you'd have to find something to bridge the two. Your example is pretty simple (being purely numbers) so a touch of REGEX (or even string.split() -- might be faster) paired with some parseInt() will allow you to quickly make a date.

如果没有的话,你就得找些东西把这两者连接起来。您的示例非常简单(纯粹是数字),所以使用REGEX(甚至string.split()——可能会更快)与parseInt()配合将使您能够快速确定日期。

#10


2  

Just to give my 5 cents.

给我5美分。

My date format is dd.mm.yyyy (UK format) and none of the above examples were working for me. All the parsers were considering mm as day and dd as month.

我的日期格式是。yyyyy(英国格式)和上面的例子没有一个对我有效。所有的解析器都将mm视为day, dd视为month。

I've found this library: http://joey.mazzarelli.com/2008/11/25/easy-date-parsing-with-javascript/ and it worked, because you can say the order of the fields like this:

我找到了这个库:http://joey.mazzarelli.com/2008/11/25/date-par- javascript/,它起作用了,因为您可以这样说字段的顺序:

>>console.log(new Date(Date.fromString('09.05.2012', {order: 'DMY'})));
Wed May 09 2012 00:00:00 GMT+0300 (EEST)

I hope that helps someone.

我希望能帮助别人。

#11


1  

Moment.js will handle this:

的时刻。js将处理这个问题:

var momentDate = moment('23.11.2009 12:34:56', 'DD.MM.YYYY HH:mm:ss');
var date = momentDate.;

#12


0  

To fully satisfy the Date.parse convert string to format dd-mm-YYYY as specified in RFC822, if you use yyyy-mm-dd parse may do a mistakes.

完全满足日期。在RFC822中,如果使用yyyy-mm-dd解析可能会出错,那么解析转换字符串的格式为dd-mm-YYYY。

#13


0  

time = "2017-01-18T17:02:09.000+05:30"

t = new Date(time)

hr = ("0" + t.getHours()).slice(-2);
min = ("0" + t.getMinutes()).slice(-2);
sec = ("0" + t.getSeconds()).slice(-2);

t.getFullYear()+"-"+t.getMonth()+1+"-"+t.getDate()+" "+hr+":"+min+":"+sec