I have a script that gets a date/time in the the format of:
2017-06-15 21:00
and then converts it to local time and displays as:
Thu Jun 15 2017 17:00:00 GMT-0400 (Eastern Daylight Time)
script:
$(document).ready(function() {
$('.plg-date > .fabrikElement > div').each(function() {
var date = $(this).text();
var newdate = new Date(date + " UTC");
console.log(newdate);
$(this).text(newdate.toString());
})
})
How would I format the toString so the output was something like this?
Thu Jun 15 2017 5:00:00 PM Eastern Daylight Time
If you can use an external library, I'd suggest this one liner using momentjs:
Using @James suggestion to use toLocaleString()
You'd have to parse it yourself. There are libraries that can do it as well (Stack Overflow rules advise not making recommendations, but if you Google "javascript date format library" a bit you'll find them), but if you want to do it with plain JavaScript, you'll just need to build the string yourself.
Since you're already creating a
Date
object, you're half way there.The
Date
object only has numbers, so it won't have strings for things likeThu
,Jun
andEastern Daylight Time
. For those, you'll need lists of possible values and to map the numbers to them (usually a simple array will work).For the
5:00:00 PM
part, you can mod (%
) the hours by 12, and then specifyAM
ifhours < 12
orPM
ifhours >= 12
.I won't give you the full JavaScript because you should take a stab at writing it yourself. If you have any trouble, please ask another question.
You can also use combinations of
toLocaleString()
, but it won't do everything you need (it doesn't do 12-hour date format, for example).