Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

mysql timestamp to time/days ago function

// in miliseconds
var units = {
  year  : 24 * 60 * 60 * 1000 * 365,
  month : 24 * 60 * 60 * 1000 * 365/12,
  day   : 24 * 60 * 60 * 1000,
  hour  : 60 * 60 * 1000,
  minute: 60 * 1000,
  second: 1000
}

var rtf = new Intl.RelativeTimeFormat('en', { numeric: 'auto' })

var getRelativeTime = (d1, d2 = new Date()) => {
  var elapsed = d1 - d2

  // "Math.abs" accounts for both "past" & "future" scenarios
  for (var u in units) 
    if (Math.abs(elapsed) > units[u] || u == 'second') 
      return rtf.format(Math.round(elapsed/units[u]), u)
}

// test-list of dates to compare with current date
[
  '10/20/1984',
  '10/20/2015',
  +new Date() - units.year,
  +new Date() - units.month,
  +new Date() - units.day,
  +new Date() - units.hour,
  +new Date() - units.minute,
  +new Date() + units.minute*2,
  +new Date() + units.day*7,
]
.forEach(d => console.log(   
  new Date(d).toLocaleDateString(),
  new Date(d).toLocaleTimeString(), 
  '(Relative to now) →',
  getRelativeTime(+new Date(d))
))
 Run code snippetHide results
Comment

PREVIOUS NEXT
Code Example
Javascript :: how to replace import with require 
Javascript :: get related through lookup using javascript in ms crm 
Javascript :: babel 7 ReferenceError: regeneratorRuntime 
Javascript :: convert javascript to jquery converter online tool 
Javascript :: concatenate to require string in solidity ethereum 
Javascript :: time zone npm in next js 
Javascript :: javascript get distance bwetween elements 
Javascript :: which element occours when a DOM element recieve the coursor 
Javascript :: Javascript multiplier function 
Javascript :: momentjs isomonth 
Javascript :: instant search initial value 
Javascript :: sharepoint javascript get last added item 
Javascript :: how to pass parameter in javascript function from html 
Javascript :: this.$moment.tz.guess() not working mozilla 
Javascript :: dynamic copyright year JavaScript centre aligned 
Javascript :: Could not parse as expression: "1, "desc" DataTable 
Javascript :: npx create-next-app permission denied 
Javascript :: how to say "and not" in javascript 
Javascript :: prepare webpack-ready 
Javascript :: how to plot a line only for current day pinescript 
Javascript :: js to ts converter 
Javascript :: date calendar show only icon click 
Javascript :: bind() method #1 
Javascript :: redwood toaster 
Javascript :: _.clone underscore 
Javascript :: prevent form submit twice jquery 
Javascript :: Backbone Sync Example 
Javascript :: Simplest Template Example 
Javascript :: Listen to custom event in Vue.js 
Javascript :: payflex api examples php 
ADD CONTENT
Topic
Content
Source link
Name
2+2 =