4
\$\begingroup\$
forceTwoDigits = (val) ->
  if val < 10
    return "0#{val}"
  return val

formatDate = (date) ->
  year = date.getFullYear()
  month = forceTwoDigits(date.getMonth()+1)
  day = forceTwoDigits(date.getDate())
  hour = forceTwoDigits(date.getHours())
  minute = forceTwoDigits(date.getMinutes())
  second = forceTwoDigits(date.getSeconds())
  return "#{year}#{month}#{day}#{hour}#{minute}#{second}"

console.log(formatDate(new Date()))

Is there a better way to do this?

\$\endgroup\$
2
\$\begingroup\$

Updated:

formatDate = (date) ->
  timeStamp = [date.getFullYear(), (date.getMonth() + 1), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds()].join(" ")
  RE_findSingleDigits = /\b(\d)\b/g

  # Places a `0` in front of single digit numbers.
  timeStamp = timeStamp.replace( RE_findSingleDigits, "0$1" )
  timeStamp.replace /\s/g, ""
\$\endgroup\$
2
  • \$\begingroup\$ Thanks!, I'm not sure doing it all at once is clearer or more maintainable though. \$\endgroup\$ – Vinko Vrsalovic Sep 9 '12 at 22:53
  • \$\begingroup\$ @VinkoVrsalovic Updated with code comment \$\endgroup\$ – Larry Battle Sep 9 '12 at 23:12
1
\$\begingroup\$

If you're happy with UTC and your JS env supports it (you can use a shim if it doesn't), you can do it as a one liner:

formatDate = (date) -> date.toISOString().replace /\..+$|[^\d]/g, ''

If you want it in the local timezone, it's a little more code:

formatDate = (date) ->
  normalisedDate = new Date(date - (date.getTimezoneOffset() * 60 * 1000))
  normalisedDate.toISOString().replace /\..+$|[^\d]/g, ''
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.