Javascript Convert Date Time string to Epoch

后端 未结 8 806
攒了一身酷
攒了一身酷 2020-11-30 09:46

so I give up...been trying to do this all day;

I have a string that supplies a date and time in the format dd/MM/yyyy hh:mm (04/12/2012 07:00

相关标签:
8条回答
  • 2020-11-30 10:11

    JavaScript dates are internally stored as milliseconds since epoch. You just need to convert it to a number, e.g. with the unary + operator, to get them. Or you can use the .getTime method.

    The harder will be parsing your date string. You likely will use a regex to extract the values from your string and pass them into Date.UTC:

    var parts = datestring.match(/(\d{2})\/(\d{2})\/(\d{4}) (\d{2}):(\d{2})/);
    return Date.UTC(+parts[3], parts[2]-1, +parts[1], +parts[4], +parts[5]);
    

    This will yield 1354604400000 ms for your example date.

    0 讨论(0)
  • 2020-11-30 10:11
    var time = new Date().getTime() / 1000 + 900 + 330*60;
    
    console.log("time = "+time);
    

    getTime() will return current time with milleseconds in last 3 digit so divide it by 1000 first. Now I have added 900 means 15 min which I need from my current time(You can delete if you do not require further delay time), 330*60(5 hr 30) is required to convert GMT time to IST which is my current region time.

    Use below site to test your time :-

    https://www.epochconverter.com/

    Hope it will help you :)

    0 讨论(0)
  • 2020-11-30 10:12
    var someDate = new Date(dateString);
    someDate = someDate.getTime();
    
    0 讨论(0)
  • 2020-11-30 10:15

    Easiest way to do is -

    const moment = require('moment')
    
    
     function getUnixTime () { return this.getTime() / 1000 | 0 }
    let epochDateTime = getUnixTime(new Date(moment().add(365, 'days').format('YYYY- 
    MM-DD hh:mm:ss')))  
    
    0 讨论(0)
  • 2020-11-30 10:16

    You can use the momentjs library to do this rather easily.

    var epoch = moment(str).unix();
    

    http://momentjs.com/

    0 讨论(0)
  • 2020-11-30 10:16

    You can use Date.parse(date).

    function epoch (date) {
      return Date.parse(date)
    }
    
    const dateToday = new Date() // Mon Jun 08 2020 16:47:55 GMT+0800 (China Standard Time)
    const timestamp = epoch(dateToday)
    
    console.log(timestamp) // => 1591606075000
    
    0 讨论(0)
提交回复
热议问题