0

I have a string like so

date = '20121217030810'

And I need to create a Date object.

So far I'm trying this

# coffeescript
if (m = /^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/.exec date)
  date = new Date("#{m[1]}-#{m[2]}-#{m[3]} #{m[4]}:#{m[5]}:#{m[6]}")
  #=> Mon Dec 17 2012 03:08:10 GMT-0600 (CST)

I just feel like there's a better way!

Any ideas?

Mulan
  • 129,518
  • 31
  • 228
  • 259

1 Answers1

1

A better way than regex? No, maybe apart from manual string splitting.

But for the Date creation, you should use

new Date(Date.UTC(+m[1], m[2]-1, +m[3], +m[4], +m[5], +m[6]))

With some coffescript sugar, you also could do

m[2] -= 1
new Date(Date.UTC(m.slice(1)...))
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • This is exactly what I was looking for. Taking this one step farther, you can do this little handy trick in coffeescript: `new Date(Date.UTC(m.slice(1)...))`. If you update your answer, I will mark it as accepted ^.^ – Mulan Dec 17 '12 at 15:33