Skip to content

Instantly share code, notes, and snippets.

@ThatGuySam
Created January 3, 2018 03:36
Show Gist options
  • Save ThatGuySam/302cb5a2496f7b86ea69abbb976cffbf to your computer and use it in GitHub Desktop.
Save ThatGuySam/302cb5a2496f7b86ea69abbb976cffbf to your computer and use it in GitHub Desktop.
Human Post Date
// Requires ES6
import moment from 'moment'
makeHumanDate (jsDateObject) {
// Now (If less than 1 minute)
// 5 mins ago (If less than 1 hours)
// 19 hrs ago (If less than 24 hours)
// Yesterday (If date is yesterday)
// Sunday (If from this week)
// August 3 (If from this year)
// December 31 2015 (If all else)
// Warn bad date
if (jsDateObject === NaN) {
console.log('Invalid Date', jsDateObject)
}
const now = new Date()
const oneMinute = 60 * 1000// Milliseconds
const oneHour = 60 * oneMinute
const oneDay = 24 * oneHour
let date = jsDateObject//moment(dateString)
let humanDate = ''
let yesterday = new Date()
yesterday.setDate(now.getDate() - 1)
console.log(moment(now.toISOString()).format('W'))
console.log(date.toISOString(), moment(date.toISOString()).format('W'))
if ( (now - date) < oneMinute ) {
humanDate = `Now`
// If less than 1 hour
// Minute Format - 5 min ago
} else if ((now - date) < oneHour) {
const minutesSince = Math.floor((now.getTime() - date.getTime()) / oneMinute)
humanDate = `${minutesSince} mins ago`
// If it's from today
// Hour Format - 5 hrs ago
} else if (now.toDateString() === date.toDateString()){
const hoursSince = Math.floor((now.getTime() - date.getTime()) / oneHour)
humanDate = `${hoursSince} hrs ago`
//If Yesterday
} else if (yesterday.toDateString() === date.toDateString()) {
humanDate = `Yesterday`
// If from this week
// Format - Sunday
} else if( moment(now.toISOString()).format('W') === moment(date.toISOString()).format('W') ) {
humanDate = moment(date).format('dddd')
// If from this year
// Format - August 8
} else if (now.getFullYear() === date.getFullYear()) {
const monthName = date.toLocaleString('en-us', { month: "long" })
const dayOfMonth = date.getDate()
humanDate = `${monthName} ${dayOfMonth}`
// Full Date
// August 8 1992
} else {
humanDate = moment(date).format('MMM D Y')
}
return humanDate
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment