简体   繁体   English

如何使用 JavaScript 中的格式规范将字符串转换为日期时间?

[英]How can I convert string to datetime with format specification in JavaScript?

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");

Use new Date( dateString ) if your string is compatible with Date.parse() .如果您的字符串与Date.parse()兼容,请使用new Date( dateString ) )。 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.如果您的格式不兼容(我认为是),您必须自己解析字符串(使用正则表达式应该很容易)并创建一个新的 Date 对象,其中包含年、月、日、小时、分钟和秒的显式值。

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上提供了示例的更新版本

@Christoph Mentions using a regex to tackle the problem. @Christoph 提到使用正则表达式来解决问题。 Here's what I'm using:这是我正在使用的:

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.它绝不是智能的,只需配置正则表达式和new Date(blah)以满足您的需求。

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但老实说,这些天我达到了像 Moment 这样的东西

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.您必须使用外部库来格式化日期输出,Flagrant Badassery 的“JavaScript Date Format”看起来很有前途。

For the input conversion, several suggestions have been made already.对于输入转换,已经提出了一些建议。 :) :)

Just for an updated answer here, there's a good js lib at http://www.datejs.com/只是为了在这里更新答案, http: //www.datejs.com/ 上有一个很好的 js 库

Datejs is an open source JavaScript Date library for parsing, formatting and processing. Datejs 是一个用于解析、格式化和处理的开源 JavaScript 日期库。

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");
}
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

External library is an overkill for parsing one or two dates, so I made my own function using Oli's and Christoph's solutions.外部库对于解析一两个日期来说太过分了,所以我使用OliChristoph 的解决方案创建了自己的函数。 Here in central Europe we rarely use aything but the OP's format, so this should be enough for simple apps used here.在中欧,我们很少使用除 OP 格式之外的任何东西,所以这对于这里使用的简单应用程序来说应该足够了。

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]));
    }
}

Date.parse() is fairly intelligent but I can't guarantee that format will parse correctly. Date.parse()相当智能,但我不能保证格式会正确解析。

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.您的示例非常简单(纯粹是数字),因此与一些parseInt()配对的 REGEX (甚至string.split()可能更快)将允许您快速确定日期。

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.我的日期格式是 dd.mm.yyyy (英国格式),以上示例均不适合我。 All the parsers were considering mm as day and dd as month.所有解析器都将 mm 视为日,将 dd 视为月。

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/easy-date-parsing-with-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.我希望这对某人有所帮助。

Moment.js will handle this: Moment.js将处理这个:

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

You can use the moment.js library for this.您可以为此使用 moment.js 库。 I am using only to get time-specific output but you can select what kind of format you want to select.我仅用于获取特定时间的输出,但您可以选择要选择的格式。

Reference:参考:

1. moment library: https://momentjs.com/ 1.时刻库: https ://momentjs.com/

2. time and date specific functions: https://timestamp.online/article/how-to-convert-timestamp-to-datetime-in-javascript 2.时间和日期具体功能: https ://timestamp.online/article/how-to-convert-timestamp-to-datetime-in-javascript

convertDate(date) {
        var momentDate = moment(date).format('hh : mm A');
        return momentDate;
}

and you can call this method like:你可以像这样调用这个方法:

this.convertDate('2020-05-01T10:31:18.837Z');

I hope it helps.我希望它有所帮助。 Enjoy coding.享受编码。

//Here pdate is the string date time
var date1=GetDate(pdate);
    function GetDate(a){
        var dateString = a.substr(6);
        var currentTime = new Date(parseInt(dateString ));
        var month =("0"+ (currentTime.getMonth() + 1)).slice(-2);
        var day =("0"+ currentTime.getDate()).slice(-2);
        var year = currentTime.getFullYear();
        var date = day + "/" + month + "/" + year;
        return date;
    }

为了完全满足Date.parse将字符串转换为 RFC822 中指定的格式 dd-mm-YYYY,如果使用 yyyy-mm-dd 解析可能会出错。

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

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