在Javascript中将日期时间字符串转换为时间戳

时间:2022-01-27 15:46:07

Question in brief:

问题简述:

What is the easiest way to convert date-month-year hour(24):minute to timestamp?

转换日期 - 月 - 年 - 小时(24):分钟到时间戳的最简单方法是什么?

due to more views add clear question on the top, so that no need to go through background & all if need quick help.

由于更多的观点在顶部添加了明确的问题,所以如果需要快速帮助,无需通过背景和所有。


Background :

I have a simple html table and I used jquery sorter to sort my table columns.

我有一个简单的html表,我使用jquery排序器来排序我的表列。

Everything is working fine except a date column which is having following format of data,

一切都工作正常,除了日期列具有以下格式的数据,

17-09-2013 10:08
date-month-year hour(24):minute

This column is sorting(alphabetically) but not as I expected(date wise). I tried to use a custom parser as follows,

此列按字母顺序排序,但不是我预期的排序(日期明确)。我尝试使用自定义解析器,如下所示,

$.tablesorter.addParser({ 
    id: 'date_column',  // my column ID
    is: function(s) { 
        return false; 
    }, 
    format: function(s) { 
        var timeInMillis = new Date.parse(s);
        return timeInMillis;         
    }, 
    type: 'numeric' 
}); 

Problem : it fails due to new Date.parse(s) .

问题:由于新的Date.parse(s)而失败。

Question : what is the easiest way to convert date-month-year hour(24):minute to timestamp? then I can skip var timeInMillis = new Date.parse(s); line.

问题:将日期 - 月 - 年 - 小时(24):分钟转换为时间戳的最简单方法是什么?然后我可以跳过var timeInMillis = new Date.parse(s);线。

Thanks

Edited :

Sorry about the confusion about milliseconds, actually it should be the timestamp which is a number that represents the current time and date.

很抱歉有关毫秒的混淆,实际上应该是时间戳,它是表示当前时间和日期的数字。

4 个解决方案

#1


26  

Parsing dates is a pain in JavaScript as there's no extensive native support. However you could do something like the following by relying on the Date(year, month, day [, hour, minute, second, millisecond]) constructor signature of the Date object.

解析日期是JavaScript的一个难点,因为没有广泛的原生支持。但是,依靠Date对象的日期(年,月,日[,小时,分钟,秒,毫秒])构造函数签名,您可以执行以下操作。

var dateString = '17-09-2013 10:08',
    dateTimeParts = dateString.split(' '),
    timeParts = dateTimeParts[1].split(':'),
    dateParts = dateTimeParts[0].split('-'),
    date;

date = new Date(dateParts[2], parseInt(dateParts[1], 10) - 1, dateParts[0], timeParts[0], timeParts[1]);

console.log(date.getTime()); //1379426880000
console.log(date); //Tue Sep 17 2013 10:08:00 GMT-0400

You could also use a regular expression with capturing groups to parse the date string in one line.

您还可以使用带有捕获组的正则表达式来解析一行中的日期字符串。

var dateParts = '17-09-2013 10:08'.match(/(\d+)-(\d+)-(\d+) (\d+):(\d+)/);

console.log(dateParts); // ["17-09-2013 10:08", "17", "09", "2013", "10", "08"]

#2


8  

Date.parse() isn't a constructor, its a static method.

Date.parse()不是构造函数,它是一个静态方法。

So, just use

所以,只需使用

var timeInMillis = Date.parse(s);

instead of

var timeInMillis = new Date.parse(s);

#3


5  

Seems like the problem is with the date format.

似乎问题是日期格式。

 var d = "17-09-2013 10:08",
 dArr = d.split('-'),
 ts = new Date(dArr[1] + "-" + dArr[0] + "-" + dArr[2]).getTime(); // 1379392680000

#4


0  

For those of us using non-ISO standard date formats, like civilian vernacular 01/01/2001 (mm/dd/YYYY), including time in a 12hour date format with am/pm marks, the following function will return a valid Date object:

对于我们这些使用非ISO标准日期格式的人,例如平民白话01/01/2001(mm / dd / YYYY),包括带有am / pm标记的12小时日期格式的时间,以下函数将返回有效的Date对象:

function convertDate(date) {

// # valid js Date and time object format (YYYY-MM-DDTHH:MM:SS)
var dateTimeParts = date.split(' ');

// # this assumes time format has NO SPACE between time and am/pm marks.
if(dateTimeParts[1].indexOf(' ') == -1 && dateTimeParts[2] === undefined) {

    var theTime = dateTimeParts[1];

    // # strip out all except numbers and colon
    var ampm = theTime.replace(/[0-9:]/g,'');

    // # strip out all except letters (for AM/PM)
    var time = theTime.replace(/[[^a-zA-Z]/g,'');

    if(ampm == 'pm') {

        time = time.split(':');

        // # if time is 12:00, don't add 12
        if(time[0] == 12) {
            time = parseInt(time[0]) + ':' + time[1] + ':00';
        } else {
            time = parseInt(time[0]) + 12 + ':' + time[1] + ':00';
        }

    } else { // if AM

        time = time.split(':');

        // # if AM is less than 10 o'clock, add leading zero
        if(time[0] < 10) {
            time = '0' + time[0] + ':' + time[1] + ':00';
        } else {
            time = time[0] + ':' + time[1] + ':00';
        }
    }
}
// # create a new date object from only the date part
var dateObj = new Date(dateTimeParts[0]);

// # add leading zero to date of the month if less than 10
var dayOfMonth = (dateObj.getDate() < 10 ? ("0"+dateObj.getDate()) : dateObj.getDate());

// # parse each date object part and put all parts together
var yearMoDay = dateObj.getFullYear() + '-' + (dateObj.getMonth() + 1) + '-' + dayOfMonth;

// # finally combine re-formatted date and re-formatted time!
var date = new Date(yearMoDay + 'T' + time);

return date;

}

Usage:

date = convertDate('11/15/2016 2:00pm');

#1


26  

Parsing dates is a pain in JavaScript as there's no extensive native support. However you could do something like the following by relying on the Date(year, month, day [, hour, minute, second, millisecond]) constructor signature of the Date object.

解析日期是JavaScript的一个难点,因为没有广泛的原生支持。但是,依靠Date对象的日期(年,月,日[,小时,分钟,秒,毫秒])构造函数签名,您可以执行以下操作。

var dateString = '17-09-2013 10:08',
    dateTimeParts = dateString.split(' '),
    timeParts = dateTimeParts[1].split(':'),
    dateParts = dateTimeParts[0].split('-'),
    date;

date = new Date(dateParts[2], parseInt(dateParts[1], 10) - 1, dateParts[0], timeParts[0], timeParts[1]);

console.log(date.getTime()); //1379426880000
console.log(date); //Tue Sep 17 2013 10:08:00 GMT-0400

You could also use a regular expression with capturing groups to parse the date string in one line.

您还可以使用带有捕获组的正则表达式来解析一行中的日期字符串。

var dateParts = '17-09-2013 10:08'.match(/(\d+)-(\d+)-(\d+) (\d+):(\d+)/);

console.log(dateParts); // ["17-09-2013 10:08", "17", "09", "2013", "10", "08"]

#2


8  

Date.parse() isn't a constructor, its a static method.

Date.parse()不是构造函数,它是一个静态方法。

So, just use

所以,只需使用

var timeInMillis = Date.parse(s);

instead of

var timeInMillis = new Date.parse(s);

#3


5  

Seems like the problem is with the date format.

似乎问题是日期格式。

 var d = "17-09-2013 10:08",
 dArr = d.split('-'),
 ts = new Date(dArr[1] + "-" + dArr[0] + "-" + dArr[2]).getTime(); // 1379392680000

#4


0  

For those of us using non-ISO standard date formats, like civilian vernacular 01/01/2001 (mm/dd/YYYY), including time in a 12hour date format with am/pm marks, the following function will return a valid Date object:

对于我们这些使用非ISO标准日期格式的人,例如平民白话01/01/2001(mm / dd / YYYY),包括带有am / pm标记的12小时日期格式的时间,以下函数将返回有效的Date对象:

function convertDate(date) {

// # valid js Date and time object format (YYYY-MM-DDTHH:MM:SS)
var dateTimeParts = date.split(' ');

// # this assumes time format has NO SPACE between time and am/pm marks.
if(dateTimeParts[1].indexOf(' ') == -1 && dateTimeParts[2] === undefined) {

    var theTime = dateTimeParts[1];

    // # strip out all except numbers and colon
    var ampm = theTime.replace(/[0-9:]/g,'');

    // # strip out all except letters (for AM/PM)
    var time = theTime.replace(/[[^a-zA-Z]/g,'');

    if(ampm == 'pm') {

        time = time.split(':');

        // # if time is 12:00, don't add 12
        if(time[0] == 12) {
            time = parseInt(time[0]) + ':' + time[1] + ':00';
        } else {
            time = parseInt(time[0]) + 12 + ':' + time[1] + ':00';
        }

    } else { // if AM

        time = time.split(':');

        // # if AM is less than 10 o'clock, add leading zero
        if(time[0] < 10) {
            time = '0' + time[0] + ':' + time[1] + ':00';
        } else {
            time = time[0] + ':' + time[1] + ':00';
        }
    }
}
// # create a new date object from only the date part
var dateObj = new Date(dateTimeParts[0]);

// # add leading zero to date of the month if less than 10
var dayOfMonth = (dateObj.getDate() < 10 ? ("0"+dateObj.getDate()) : dateObj.getDate());

// # parse each date object part and put all parts together
var yearMoDay = dateObj.getFullYear() + '-' + (dateObj.getMonth() + 1) + '-' + dayOfMonth;

// # finally combine re-formatted date and re-formatted time!
var date = new Date(yearMoDay + 'T' + time);

return date;

}

Usage:

date = convertDate('11/15/2016 2:00pm');