繁体   English   中英

如何将日期转换为时间戳?

[英]How to convert date to timestamp?

我想将日期转换为时间戳,我的输入是26-02-2012 我用了

new Date(myDate).getTime();

它说 NaN.. 谁能告诉我如何转换它?

将字符串拆分为各个部分,并将它们直接提供给 Date 构造函数:

更新:

 var myDate = "26-02-2012"; myDate = myDate.split("-"); var newDate = new Date( myDate[2], myDate[1] - 1, myDate[0]); console.log(newDate.getTime());

试试这个函数,它使用Date.parse()方法并且不需要任何自定义逻辑:

function toTimestamp(strDate){
   var datum = Date.parse(strDate);
   return datum/1000;
}
alert(toTimestamp('02/13/2009 23:31:30'));

这个重构的代码会做到这一点

let toTimestamp = strDate => Date.parse(strDate)

这适用于所有现代浏览器,除了 ie8-

var dtstr = "26-02-2012";
new Date(dtstr.split("-").reverse().join("-")).getTime();

这里有两个问题。 首先,您只能在日期实例上调用 getTime。 您需要将新日期括在括号中或将其分配给变量。

其次,您需要以适当的格式向其传递一个字符串。

工作示例:

(new Date("2012-02-26")).getTime();

如果您来这里寻找当前时间戳

var date      = new Date();
var timestamp = date.getTime();

或者干脆

new Date().getTime();
/* console.log(new Date().getTime()); */

您只需要反转您的日期数字并更改-,

new Date(2012,01,26).getTime(); // 02 becomes 01 because getMonth() method returns the month (from 0 to 11)

在你的情况下:

var myDate="26-02-2012";
myDate=myDate.split("-");
new Date(parseInt(myDate[2], 10), parseInt(myDate[1], 10) - 1 , parseInt(myDate[0]), 10).getTime();

PS UK 语言环境在这里无关紧要。

要将(ISO)日期转换为Unix 时间戳,我最终得到的时间戳比需要的长 3 个字符,所以我的年份大约是 50k...

我不得不将它除以 1000: new Date('2012-02-26').getTime() / 1000

function getTimeStamp() {
       var now = new Date();
       return ((now.getMonth() + 1) + '/' + (now.getDate()) + '/' + now.getFullYear() + " " + now.getHours() + ':'
                     + ((now.getMinutes() < 10) ? ("0" + now.getMinutes()) : (now.getMinutes())) + ':' + ((now.getSeconds() < 10) ? ("0" + now
                     .getSeconds()) : (now.getSeconds())));
}

对于那些想要格式为yyyymmddHHMMSS的可读时间戳的人

> (new Date()).toISOString().replace(/[^\d]/g,'')              // "20190220044724404"
> (new Date()).toISOString().replace(/[^\d]/g,'').slice(0, -3) // "20190220044724"
> (new Date()).toISOString().replace(/[^\d]/g,'').slice(0, -9) // "20190220"

使用示例:备份文件扩展名。 /my/path/my.file.js.20190220

您的字符串不是Date对象指定要处理的格式。 您必须自己解析它,使用像MomentJS或更旧的日期解析库(据我所知,目前尚未维护) DateJS ,或者将其按摩成正确的格式(例如, 2012-02-29 )在要求Date解析它之前。

为什么你得到NaN :当你要求new Date(...)处理一个无效的字符串时,它会返回一个设置为无效日期的Date对象( new Date("29-02-2012").toString()返回"Invalid date" )。 在此状态下对日期对象调用getTime()会返回NaN

/**
 * Date to timestamp
 * @param  string template
 * @param  string date
 * @return string
 * @example         datetotime("d-m-Y", "26-02-2012") return 1330207200000
 */
function datetotime(template, date){
    date = date.split( template[1] );
    template = template.split( template[1] );
    date = date[ template.indexOf('m') ]
        + "/" + date[ template.indexOf('d') ]
        + "/" + date[ template.indexOf('Y') ];

    return (new Date(date).getTime());
}

下面的代码会将当前日期转换为时间戳。

var currentTimeStamp = Date.parse(new Date());
console.log(currentTimeStamp);

它应该采用此标准日期格式 YYYY-MM-DD,以使用以下等式。 您可能有时间,例如:2020-04-24 16:51:56 或 2020-04-24T16:51:56+05:30。 它可以正常工作,但日期格式应该只像这个 YYYY-MM-DD。

var myDate = "2020-04-24";
var timestamp = +new Date(myDate)

第一个答案很好,但是使用 react typescript 会抱怨因为 split('') 对我来说效果更好的方法是。

parseInt((new Date("2021-07-22").getTime() / 1000).toFixed(0))

乐意效劳。

您可以使用valueOf方法

new Date().valueOf()

在某些情况下,某些日期似乎很顽固,也就是说,即使使用日期格式,例如“2022-06-29 15:16:21”,您仍然会得到 null 或 NaN。 我必须通过在空白处包含一个“T”来解决我的问题,即:

const inputDate = "2022-06-29 15:16:21";
const newInputDate = inputDate.replace(" ", "T");

const timeStamp = new Date(newInputDate).getTime();

这对我来说很好! 干杯!

其他开发人员已提供了答案,但以我自己的方式,您可以即时执行此操作,而无需创建任何用户定义的函数,如下所示:

var timestamp = Date.parse("26-02-2012".split('-').reverse().join('-'));
alert(timestamp); // returns 1330214400000

只需对Date对象执行一些算术运算,就会将时间戳作为number返回。 这对于紧凑符号很有用。 我发现这是最容易记住的方法,因为该方法也适用于将转换为string类型的数字转换回number类型。

 let d = new Date(); console.log(d, d * 1);

如果您还需要添加时间new Date('2021-07-22 07:47:05.842442+00').getTime()

这也适用于没有 Time new Date('2021-07-22 07:47:05.842442+00').getTime()

这也可以,但它不会 Accept Time new Date('2021/07/22').getTime()

最后,如果一切都不起作用,请使用这个new Date(year, month, day, hours, minutes, seconds, milliseconds)

注意月份,计数从0开始,所以Jan === 0Dec === 11

一张照片说一千个字:)

在这里,我将当前日期转换为时间戳,然后获取时间戳并将其转换为当前日期,我们将展示如何将日期转换为时间戳以及将时间戳转换为日期。

在此处输入图像描述

最简单和准确的方法是在日期之前添加一元运算符

 console.log(`Time stamp is: ${Number(+new Date())}`)

只是提醒

Date.parse("2022-08-04T04:02:10.909Z")

1659585730909

Date.parse(新日期("2022-08-04T04:02:10.909Z"))

1659585730000

+new Date(myDate)这应该将 myDate 转换为 timeStamp

暂无
暂无

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

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