Last active
December 1, 2020 18:57
-
-
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
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
// 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