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
  • 119,326
  • 28
  • 214
  • 246

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
  • 572,313
  • 128
  • 898
  • 1,281
  • 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