convert date to timestamp in javascript?

2019-01-03 05:20发布

I want to convert date to timestamp, my input is 26-02-2012. I used

new Date(myDate).getTime();

It says NaN.. Can any one tell how to convert this?

10条回答
▲ chillily
2楼-- · 2019-01-03 05:31

Your string isn't in a format that the Date object is specified to handle. You'll have to parse it yourself, use a date parsing library like MomentJS or the older (and not currently maintained, as far as I can tell) DateJS, or massage it into the correct format (e.g., 2012-02-29) before asking Date to parse it.

Why you're getting NaN: When you ask new Date(...) to handle an invalid string, it returns a Date object which is set to an invalid date (new Date("29-02-2012").toString() returns "Invalid date"). Calling getTime() on a date object in this state returns NaN.

查看更多
霸刀☆藐视天下
3楼-- · 2019-01-03 05:32

You need just to reverse your date digit and change - with ,:

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

In your case:

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

P.S. UK locale does not matter here.

查看更多
爷、活的狠高调
4楼-- · 2019-01-03 05:40

Try this function, it uses the Date.parse() method and doesn't require any custom logic:

function toTimestamp(strDate){
   var datum = Date.parse(strDate);
   return datum/1000;
}
alert(toTimestamp('02/13/2009 23:31:30'));
查看更多
你好瞎i
5楼-- · 2019-01-03 05:40
var dtstr = "26-02-2012";
new Date(dtstr.split("-").reverse().join("-")).getTime();
查看更多
我只想做你的唯一
6楼-- · 2019-01-03 05:40
/**
 * 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());
}
查看更多
甜甜的少女心
7楼-- · 2019-01-03 05:41
var myDate="26-02-2012";
myDate=myDate.split("-");
var newDate=myDate[1]+","+myDate[0]+","+myDate[2];
alert(new Date(newDate).getTime());​ //will alert 1330192800000

Update:

var myDate="26-02-2012";
myDate=myDate.split("-");
var newDate=myDate[1]+"/"+myDate[0]+"/"+myDate[2];
alert(new Date(newDate).getTime()); //will alert 1330210800000

DEMO (Tested in Chrome, FF, Opera, IE and Safari).

查看更多
登录 后发表回答