Skip to content

Instantly share code, notes, and snippets.

@gwhitelaw
Last active December 25, 2015 21:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gwhitelaw/7040178 to your computer and use it in GitHub Desktop.
Save gwhitelaw/7040178 to your computer and use it in GitHub Desktop.
Allow sugarjs to parse multiple friendly dates in the format 1 month 1 day ago
require 'sugar'
{ compact } = require 'underscore'
parseFriendlyDate = (friendlyDate) ->
date = new Date().getTime()
dateOffset = date
dateSections = compact((friendlyDate.trim()).split(/(\d+\s\w+)\s/))
dateEnding = dateSections.splice(-1)
dateSections.forEach((section) -> dateOffset -= (date - Date.create("#{section} #{dateEnding}").getTime()))
new Date(dateOffset)
console.log(parseFriendlyDate('1 day ago'))
console.log(parseFriendlyDate('1 day 1 month ago'))
console.log(parseFriendlyDate('1 year 1 month 1 day ago'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment