Skip to content

Instantly share code, notes, and snippets.

@volomike
Created January 2, 2021 01:00
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 volomike/00ca85b550eb6901670afad6a4134501 to your computer and use it in GitHub Desktop.
Save volomike/00ca85b550eb6901670afad6a4134501 to your computer and use it in GitHub Desktop.
Minimalist jQuery Local Date/Time Script Without Moment.js
$(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'));
});
});
@volomike
Copy link
Author

volomike commented Jan 2, 2021

This wouldn't take much to convert it from jQuery to Vanilla Javascript. Instead of $(sel), use document.querySelectorAll(sel). Instead of .each(function(){...});, use .forEach(function(el,i){...};. Instead of $(this), use el in the forEach(function(el,i){...}); loop. Instead of .text, use .innerText and as an assignment instead of function. Instead of $(document).ready(function(){...}, use document.addEventListener("DOMContentLoaded", function(event) {...}.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment