Sign up ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.
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

2 Answers 2

up vote 1 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.