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

问题描述 投票:0回答:25

我想将日期转换为时间戳,我的输入是

26-02-2012
。我用过

new Date(myDate).getTime();

它说 NaN ..任何人都可以告诉如何转换它吗?

javascript date time
25个回答
305
投票

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

更新:

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

更新: 另外,还可以使用正则表达式来分割字符串,例如:

const dtStr = "26/02/2012";
const [d, m, y] = dtStr.split(/-|\//); // splits "26-02-2012" or "26/02/2012"
const date = new Date(y, m - 1, d);
console.log(date.getTime());


98
投票

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

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

53
投票

这个重构的代码就可以了

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

这适用于除 ie8 之外的所有现代浏览器-


24
投票

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

其次,您需要向其传递一个正确格式的字符串。

工作示例:

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

19
投票

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

Date.now(); //as suggested by Wilt

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

或者简单地

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

12
投票

您只需反转日期数字并将

-
更改为
,
:

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

附注英国语言环境在这里并不重要。


8
投票

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

我必须将它除以 1000:

new Date('2012-02-26').getTime() / 1000


6
投票
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())));
}

6
投票

只是一个提醒

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

Date.parse(new Date("2022-08-04T04:02:10.909Z"))
// 1659585730000 (milliseconds are ignored)

4
投票

您的字符串不是

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

为什么你会得到

NaN

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


4
投票
对于那些想要具有以下格式的可读时间戳的人,

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


    


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

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

2
投票
/** * 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()); }
    

2
投票
第一个答案很好,但是使用反应打字稿会因为 split('') 而抱怨 对我来说,效果更好的方法是。

parseInt((new Date("2021-07-22").getTime() / 1000).toFixed(0))
很乐意提供帮助。


2
投票
在某些情况下,某些日期似乎很顽固,也就是说,即使使用日期格式,例如“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();
这对我来说效果很好!干杯!


1
投票
它应该采用标准日期格式 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)
    

1
投票
可以使用

valueOf

方法

new Date().valueOf()
    

1
投票
最简单、准确的方法是在日期前添加一元运算符

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


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

var date = new Date(); var timestamp = date.getTime(); console.log(timestamp) // 1654636718244 var actual = new Date(timestamp) console.log(actual) // Tue Jun 07 2022 18:18:38 GMT-0300 (Horário Padrão de Brasília)
    

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

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

0
投票
简单地对

Date

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

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


0
投票
如果您还需要增加时间,这会起作用

new Date('2021-07-22 07:47:05.842442+00').getTime()


没有时间这也可以工作

new Date('2021-07-22 07:47:05.842442+00').getTime()


这也可以,但它不会接受时间

new Date('2021/07/22').getTime()


最后,如果一切都不起作用,请使用这个

new Date(year, month, day, hours, minutes, seconds, milliseconds)


注意月份,计数从 0

 开始,因此 
Jan === 0
Dec === 11


0
投票

+new Date(myDate)

这应该将 myDate 转换为时间戳


0
投票
就这么简单,但您必须确保使用

american 日期格式

function MygetTime(date){ return (new Date(date).getTime()) } console.log(MygetTime("03-13-2023"))


0
投票
我用它来获取我的时间戳:

Date.parse("2000-03-04 09:10:43")/1000;


    

© www.soinside.com 2019 - 2024. All rights reserved.