Skip to content

Instantly share code, notes, and snippets.

@miklund
Created January 11, 2016 09:22
Show Gist options
  • Save miklund/f08f1247b585e7806574 to your computer and use it in GitHub Desktop.
Save miklund/f08f1247b585e7806574 to your computer and use it in GitHub Desktop.
2012-05-29 Time in a global space
# Title: Time in a global space
# Author: Mikael Lundin
# Link: http://blog.mikaellundin.name/2012/05/29/time-in-a-global-space.html
<li>
<!-- Removed unimportant markup for brevity -->
<time datetime="2012-05-29T08:29:51Z">2012-05-29T08:29:51Z</time>
</li>
<li>
<!-- ... -->
<time datetime="2012-05-28T15:16:24Z">2012-05-28T15:16:24Z</time>
</li>
<li>
<!-- ... -->
<time datetime="2012-05-28T08:05:38Z">2012-05-28T08:05:38Z</time>
</li>
<li>
<!-- ... -->
<time datetime="2012-05-26T08:36:20Z">2012-05-26T08:36:20Z</time>
</li>
# parse string '2012-05-05T16:16:34Z' to datetime
parse_datetime = (str) ->
exp = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/
date = new Date()
parts = exp.exec(str)
# not correct format
throw "Failed to parse as time: #{str}" unless parts
month = +parts[2]
date.setUTCFullYear(parts[1], month - 1, parts[3])
date.setUTCHours(parts[4], parts[5], parts[6])
return date
# helpers for formatting dates
format =
# These might have to be globalized in the future
weekdays : ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],
# These might have to be globalized in the future
months : [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ],
# get hours from date with leading zero
getHours : ((date) -> if date.getHours() < 10 then "0#{date.getHours()}" else "#{date.getHours()}"),
# get minutes from date with leading zero
getMinutes : ((date) -> if date.getMinutes() < 10 then "0#{date.getMinutes()}" else "#{date.getMinutes()}"),
# transform all timestamps on page
for time in $('time')
# get localized time
published = parse_datetime(time.attr('datetime'))
# ommitting code for all if today, if yesterday, if this week....
# Format: 18 January, 12:34
time.text("#{published.getDate()} #{format.months[published.getMonth()]} #{published.getFullYear()}, #{format.getHours(published)}:#{format.getMinutes(published)}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment