Skip to content

Instantly share code, notes, and snippets.

@robpataki
Created September 19, 2018 12:35
Show Gist options
  • Save robpataki/f8d770930e625e38287e5c67482cebcc to your computer and use it in GitHub Desktop.
Save robpataki/f8d770930e625e38287e5c67482cebcc to your computer and use it in GitHub Desktop.
Display moment style dates in the front-end
/*
Example usage:
<span class="moment" data-moment="add 12 days"></span>
*/
'use strict'
import moment from 'moment'
/* TimeTravel */
const TimeTravel = function () {
const $moments = document.querySelectorAll('.moment')
$moments.forEach(function ($el, index) {
const rightNow = moment(new Date())
const data = $el.getAttribute('data-moment')
let date = ''
if (data) {
const config = data.split(' ')
if (config.length === 3) {
const configObj = {
method: config[0] === 'add' ? 'add' : 'subtract',
amount: parseInt(config[1]),
unit: config[2] === 'days' ||
config[2] === 'weeks' ||
config[2] === 'months' ||
config[2] === 'years' ? config[2] : ''
}
if (typeof configObj !== 'undefined' && configObj.unit.length) {
date = rightNow[configObj.method](configObj.amount, configObj.unit)
}
}
}
date = rightNow.format('DD MM YYYY')
$el.innerHTML = date
})
}
export default {
init: TimeTravel
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment