Skip to content

Instantly share code, notes, and snippets.

@GiancarloGomez
Last active December 1, 2020 18:57
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 GiancarloGomez/f7844fdff944be83e203eb61f0481ab9 to your computer and use it in GitHub Desktop.
Save GiancarloGomez/f7844fdff944be83e203eb61f0481ab9 to your computer and use it in GitHub Desktop.
Using moment.js and jQuery to render a local date inside an element that has a UTC value in a data-date attribute
// requires moment.js and jQuery
/**
* @value A datetime string value formatted as 01/01/01 12:00:00 AM
*/
function convertDateToLocal( value ){
return moment( value.replace(/\s(GMT|UTC)/,'') )
.add( moment().utcOffset(),'m' )
.format( 'MM/DD/YYYY hh:mm:ss A' );
}
/**
* @elem An HTML element
*/
function parseDateInElement( elem ){
var me = $( elem ),
date = me.data('date');
if ( date !== '' ){
date = convertDateToLocal( date );
if (elem.tagName.toLowerCase() === 'input')
me.val( date );
else
me.html( date );
}
}
/**
* @elem A jQuery Object to check and parse
* ( good for an element that is updated anytime after load - ie: Ajax call )
*/
function parseDatesInContainer( elem ){
elem.find('[data-date]').each(function(){
parseDateInElement( this )
});
}
$(function(){
$('[data-date]').each(function(){
parseDateInElement( this )
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment