将日期时间字符串转换为Javascript中的时间戳 [英] Converting a datetime string to timestamp in Javascript

查看:136
本文介绍了将日期时间字符串转换为Javascript中的时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简短问题:

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

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

由于有更多的视图,因此在顶部添加了明确的问题,因此无需了解背景&全部需要快速帮助.

背景:

我有一个简单的html表,并且使用 jquery排序器来对我的表列进行排序.

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

除日期列具有以下数据格式外,其他所有内容都正常运行

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

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

问题:date-month-year hour(24):minute转换为时间戳的最简单方法是什么?那么我可以跳过var timeInMillis = new 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.

谢谢

抱歉,关于milliseconds的困惑,实际上应该是timestamp,它是代表当前时间和日期的数字.

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

推荐答案

在JavaScript中,解析日期很麻烦,因为它没有广泛的本机支持.但是,您可以依靠Date(year, month, day [, hour, minute, second, millisecond])构造函数签名来执行以下操作. rel ="noreferrer"> Date 对象.

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.

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"]

这篇关于将日期时间字符串转换为Javascript中的时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆