Javascript Convert Date Time string to Epoch

后端 未结 8 837
攒了一身酷
攒了一身酷 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.

提交回复
热议问题