Converting Date and Time To Unix Timestamp

JavascriptRegexUnixTimestamp

Javascript Problem Overview


I'm displaying the date and time like this

> 24-Nov-2009 17:57:35

I'd like to convert it to a unix timestamp so I can manipulate it easily. I'd need to use regex to match each part of the string then work out the unix timestamp from that.

I'm awful with regex but I came up with this. Please suggest improvements ^.^

/((\d){2}+)-((Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)+)-((\d){4}+) ((\d){2}+):((\d){2}+):((\d){2}+)/gi

How can I do this?

Javascript Solutions


Solution 1 - Javascript

If you just need a good date-parsing function, I would look at date.js. It will take just about any date string you can throw at it, and return you a JavaScript Date object.

Once you have a Date object, you can call its getTime() method, which will give you milliseconds since January 1, 1970. Just divide that result by 1000 to get the unix timestamp value.

In code, just include date.js, then:

var unixtime = Date.parse("24-Nov-2009 17:57:35").getTime()/1000

Solution 2 - Javascript

Seems like getTime is not function on above answer.

Date.parse(currentDate)/1000

Solution 3 - Javascript

You can use Date.getTime() function, or the Date object itself which when divided returns the time in milliseconds.

var d = new Date();

d/1000
> 1510329641.84

d.getTime()/1000
> 1510329641.84

Solution 4 - Javascript

Using a date picker to get date and a time picker I get two variables, this is how I put them together in unixtime format and then pull them out...

let datetime = oDdate+' '+oDtime;
let unixtime = Date.parse(datetime)/1000;
console.log('unixtime:',unixtime);

to prove it:

let milliseconds = unixtime * 1000;
dateObject = new Date(milliseconds);
console.log('dateObject:',dateObject);

enjoy!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBen ShelockView Question on Stackoverflow
Solution 1 - JavascriptIan ClellandView Answer on Stackoverflow
Solution 2 - JavascriptchovyView Answer on Stackoverflow
Solution 3 - JavascriptXeoncrossView Answer on Stackoverflow
Solution 4 - JavascriptDavid WhiteView Answer on Stackoverflow