The Spaghetti Refactory Established 2015

Handling datetime in JavaScript (or more accurately, CoffeeScript)

Working with Date, Time, and DateTime seems to be pretty awful in any language, but compared to Ruby and ActiveSupport, doing it in JS or Coffee is awful. You can get libraries that make it a little easier to work with (I believe Moment.js is one such that can be very helpful), but for simple formatting things, it's easier and more lightweight to just write your own functions.

 This gives today‚Äôs date in YYYY-MM-DD format:

date_today = ->
today = new Date()
dd = today.getDate()
mm = today.getMonth() + 1
yyyy = today.getFullYear()
if dd < 10
dd = '0' + dd
if mm < 10
mm = '0' + mm
today = yyyy+'-'+mm+'-'+dd
return today

This gives the current time in HH:MM:SS -0800 format, where -0800 is the timezone offset from GMT, and the HH are displayed in 24 hour time:

time_now = ->
right_now = new Date()
hh = right_now.getHours()
mm = right_now.getMinutes()
ss = right_now.getSeconds()
time_zone = right_now.toString().split(':')[2].substr(6, 5)
if time_zone == ""
time_zone = "UTC"
right_now = hh+':'+mm+':'+ss+' '+time_zone
return right_now

Tags