Created
January 2, 2021 01:00
-
-
Save volomike/00ca85b550eb6901670afad6a4134501 to your computer and use it in GitHub Desktop.
Minimalist jQuery Local Date/Time Script Without Moment.js
This file contains hidden or 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
$(document).ready(function(){ | |
// Convert RFC2822 date/time string to local date/time in format MM/DD/YYYY HH:MM XM. | |
// Note that PHP has a date format of 'r' that generates RFC2822 format. | |
// Wrap your RFC2822 HTML element with the localdate class and this function converts it. | |
$('.localdate').each(function(){ | |
var o = $(this); | |
var d = new Date(o.text()); | |
var s = d.toLocaleString(); | |
s = s.replace(/(?<!\d)(\d)(?!\d)/g,'0$1'); | |
var a = s.split(':'); | |
var n = '' + a[0]; | |
n += ':' + a[1]; | |
var a2 = s.split(' '); | |
n += ' ' + a2.pop(); | |
n = n.split(',').join(''); | |
o.text(n); | |
}); | |
// Handy function to display a 3 digit timezone code that also accounts for daylight savings time for the given user's local timezone. | |
$('.timezonecode').each(function(){ | |
var o = $(this); | |
o.text((new Date()).toString().match(/\(.*\)/)[0].match(/\b(\w)/g).join('').split('CUT').join('UTC')); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This wouldn't take much to convert it from jQuery to Vanilla Javascript. Instead of
$(sel)
, usedocument.querySelectorAll(sel)
. Instead of.each(function(){...});
, use.forEach(function(el,i){...};
. Instead of$(this)
, useel
in theforEach(function(el,i){...});
loop. Instead of.text
, use.innerText
and as an assignment instead of function. Instead of$(document).ready(function(){...}
, usedocument.addEventListener("DOMContentLoaded", function(event) {...}
.