Convert normal date to unix timestamp

前端 未结 11 907
小鲜肉
小鲜肉 2020-11-28 05:10

How can I convert normal date 2012.08.10 to unix timestamp in javascript?

Fiddle: http://jsfiddle.net/J2pWj/




I\'ve se

相关标签:
11条回答
  • 2020-11-28 05:44
    var datestr = '2012.08.10';
    var timestamp = (new Date(datestr.split(".").join("-")).getTime())/1000;
    
    0 讨论(0)
  • 2020-11-28 05:56

    You could simply use the unary + operator

    (+new Date('2012.08.10')/1000).toFixed(0);

    http://xkr.us/articles/javascript/unary-add/ - look under Dates.

    0 讨论(0)
  • 2020-11-28 05:57
    var date = new Date('2012.08.10');
    var unixTimeStamp = Math.floor(date.getTime() / 1000);
    

    In this case it's important to return only a whole number (so a simple division won't do), and also to only return actually elapsed seconds (that's why this code uses Math.floor() and not Math.round()).

    0 讨论(0)
  • 2020-11-28 05:59

    You should check out the moment.js api, it is very easy to use and has lots of built in features.

    I think for your problem, you could use something like this:

    var unixTimestamp = moment('2012.08.10', 'YYYY.MM.DD').unix();
    
    0 讨论(0)
  • 2020-11-28 06:00

    After comparing timestamp with the one from PHP, none of the above seems correct for my timezone. The code below gave me same result as PHP which is most important for the project I am doing.

    function getTimeStamp(input) {
        var parts = input.trim().split(' ');
        var date = parts[0].split('-');
    	var time = (parts[1] ? parts[1] : '00:00:00').split(':');
    
    	// NOTE:: Month: 0 = January - 11 = December.
    	var d = new Date(date[0],date[1]-1,date[2],time[0],time[1],time[2]);
    	return d.getTime() / 1000;
    }
    
    // USAGE::
    var start = getTimeStamp('2017-08-10');
    var end = getTimeStamp('2017-08-10 23:59:59');
    
    console.log(start + ' - ' + end);

    I am using this on NodeJS, and we have timezone 'Australia/Sydney'. So, I had to add this on .env file:

    TZ = 'Australia/Sydney'
    

    Above is equivalent to:

    process.env.TZ = 'Australia/Sydney'
    
    0 讨论(0)
  • 2020-11-28 06:01
    parseInt((new Date('2012.08.10').getTime() / 1000).toFixed(0))
    

    It's important to add the toFixed(0) to remove any decimals when dividing by 1000 to convert from milliseconds to seconds.

    The .getTime() function returns the timestamp in milliseconds, but true unix timestamps are always in seconds.

    0 讨论(0)
提交回复
热议问题