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 Answers 2

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\$ Commented Sep 9, 2012 at 22:53
  • \$\begingroup\$ @VinkoVrsalovic Updated with code comment \$\endgroup\$ Commented Sep 9, 2012 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\$

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.