My CMS doesn’t allow me to reformat a date string on the back end, so I’m converting the text on the front end with Javascript.
This are some examples of what the CMS produces:
Sunday, November 11, 2012, 4:45 PM - 6:00 PMEvery Sunday , 9:15 AM - 10:30 AMFirst Sunday of the month, 9:15 AM - 1:00 PM - Rm 306Every Wednesday, 5:30 PM - 8:30 PM, from 09/05/2012 to 11/14/2012
Here’s how I want it to be formatted:
Sun, Nov 11 @ 4:45-6p(Short day & month name, no year, no trailing :00)Every Sun @ 9:15-10:30a(no AM/PM indicator on the first time if they’re both AM or PM)First Sun of the month @ 9:15a-1p(Lowercase A & P)Every Wed @ 5:30-8:30p, Sep 5-Nov 14(Show months on date span, remove year, remove leading 0 on dates)
So here’s the function I’ve come up with:
$(".smart-time").each(function(){
$(this).html($(this).html()
.replace(/( *)?-( *)?([0-9]([0-2])?:[0-5][0-9])/gi,"-$3") // Remove space in dashes between time
.replace(/(:[0-5][0-9])([ ]?AM)/gi,"$1a") // Short AM
.replace(/(:[0-5][0-9])([ ]?PM)/gi,"$1p") // Short PM
.replace(/12:00( )?p/gi,"Noon") // 12:00p = Noon
.replace(/12:00( )?a/gi,"Midnight") // 12:00a = Midnight
.replace(/(:00| from)/gi,"") // No trailing :00
.replace(/([0-9:]*)a-([0-9:]*)a/gi,"$1-$2a") // Remove first 'a' in span
.replace(/([0-9:]*)p-([0-9:]*)p/gi,"$1-$2p") // Remove first 'p' in span
.replace(/(\, |\/)(20[0-9][0-9])/gi,"") // Remove Year
.replace(/ to /gi,"-") // to changed to -
.replace(/\/(0)?([0-9]*)/gi,"/$2") // Remove leading 0 in dates
.replace(/01\//gi,"Jan ") // Change month number to short name
.replace(/02\//gi,"Feb ")
.replace(/03\//gi,"Mar ")
.replace(/04\//gi,"Apr ")
.replace(/05\//gi,"May ")
.replace(/06\//gi,"Jun ")
.replace(/07\//gi,"Jul ")
.replace(/08\//gi,"Aug ")
.replace(/09\//gi,"Sep ")
.replace(/10\//gi,"Oct ")
.replace(/11\//gi,"Nov ")
.replace(/12\//gi,"Dec ")
.replace(/(Sun|Mon|Tue|Wed|Thu|Fri|Sat)(s|nes|rs|ur)?day/gi,"$1") // Shorten Day names
.replace(/\, <\/span>/gi," @ </span>") // Change , to @
.replace(/(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)((r)?uary|(t)?(em)?(o)?ber|ch|il|e|y|ust)?/gi,"$1") // Shorten Month names
);
});
This works, but it feels very… bulky.
Is there a better way to do this or a simpler way to accomplish the same goal?
Another option worth considering is the jQuery UI Datepicker’s
parseDate()method, documented here.However, while this is very easy to use, it’s clearly only practical if you’re already using datepicker on your site.