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

new Date(myDate).getTime();

上面写着NaN..有人能告诉我怎么转换吗?


当前回答

第一个答案是好的,但是使用react typescript会报错,因为split(") 对我来说,更好的方法是。

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

很乐意帮忙。

其他回答

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

var currentTimeStamp = Date.parse(new Date());
console.log(currentTimeStamp);
/**
 * 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());
}

一幅图胜过千言万语:)

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

在某些情况下,某些日期似乎是顽固的,也就是说,即使使用日期格式,如“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();

这对我来说很有效!干杯!

你只需要倒转你的日期数字,然后用,

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

附注:英国地区在这里并不重要。