Created
September 19, 2018 12:35
-
-
Save robpataki/f8d770930e625e38287e5c67482cebcc to your computer and use it in GitHub Desktop.
Display moment style dates in the front-end
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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