Javascript Convert Date Time string to Epoch

谁说我不能喝 提交于 2019-12-17 09:47:02

问题


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).

I need to turn that into an Epoch date so I can do some calculations upon it. I cannot modify the format in which the date time is sent to me.

JavaScript or jQuery is fine.


回答1:


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.




回答2:


var someDate = new Date(dateString);
someDate = someDate.getTime();



回答3:


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

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

http://momentjs.com/




回答4:


i used this code to convert my string datetime to epoch

new Date(<datetime string>').getTime()

for example :

let epoch = new Date('2016-10-11').getTime()



回答5:


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 :)




回答6:


My answer is to convert current time to epoch time using JavaScript

const currentDate = Math.floor(new Date() / 1000);

console.log(currentDate); //whatever value it will print you can check the same value to this website https://www.epochconverter.com/ to confirm.




回答7:


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')))  


来源:https://stackoverflow.com/questions/13707333/javascript-convert-date-time-string-to-epoch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!