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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18849351/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 22:37:11  来源:igfitidea点击:

Converting a datetime string to timestamp in Javascript

javascriptjquery

提问by Janith Chinthana

Question in brief:

问题简述:

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

什么是转换的最简单的方法date-month-year hour(24):minutetimestamp

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 sorterto 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).

问题:由于new Date.parse(s).

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

问题:转换date-month-year hour(24):minute为时间戳的最简单方法是什么?然后我可以跳过var timeInMillis = new Date.parse(s);线。

Thanks

谢谢

Edited :

编辑:

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

很抱歉关于 的混淆milliseconds,实际上它应该是timestamp代表当前时间和日期的数字。

回答by plalx

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 Dateobject.

解析日期在 JavaScript 中很痛苦,因为没有广泛的本机支持。但是,您可以通过依赖对象的Date(year, month, day [, hour, minute, second, millisecond])构造函数签名来执行以下操作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"]

回答by Rémi Becheras

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

回答by Rémi Becheras

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

回答by recurse

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