views:

470

answers:

3

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?

+3  A: 

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
Ian Clelland
You don't even need the library to parse that format, do you?
Dexter
It's worth noting that without date.js, Date.parse will take a string and return a unix timestamp. But it's very strict about the format. In the OP's example, you would need to string.replace('-', '/'). Other than that, I'm pretty sure it would work in all modern browsers.I agree that date.js is much more reliable though.
Marco
stick to your regexp. A localized javascript library is overkill if you are using a fixed date format. If you have control over this format, you should consider using something more neutral and easier to parse, like ISO8601.
peller
@Marco: I didn't even bother trying the native <code>Date.parse</code> method -- That exact format works in Chrome, but returns NaN in Firefox (it works with "/" in both, though)
Ian Clelland
Ahh - I only tested in Chrome.. that explains my confusion!
Dexter
A: 

Why not do it this way, as a hint,

long lUnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0).Ticks; 

That sets up lUnixEpoch to be the date when the original Unix system started.

Hope this helps, Best regards, Tom.

tommieb75