Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top
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?

share|improve this question
up vote 2 down vote accepted


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, ""
share|improve this answer
Thanks!, I'm not sure doing it all at once is clearer or more maintainable though. – Vinko Vrsalovic Sep 9 '12 at 22:53
@VinkoVrsalovic Updated with code comment – Larry Battle Sep 9 '12 at 23:12

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, ''
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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