简体   繁体   中英

Javascript Date toString convert and format to local time

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

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 like Thu , Jun and Eastern 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 specify AM if hours < 12 or PM if hours >= 12 .

const time = (d.getHours() % 12) + ':' + d.getMinutes() + ':' + d.getSeconds() + (d.getHours() < 12 ? 'AM' : 'PM');

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).

If you can use an external library, I'd suggest this one liner using momentjs :

moment('2017-06-15 21:00').format('ddd MMM DD YYYY h:mm:ss A')
// => "Thu Jun 15 2017 9:00:00 PM"

Using @James suggestion to use toLocaleString()

$(document).ready(function() {
    $('.plg-date > .fabrikElement > div').each(function() {
        if($(this).text().length > 0) {
            var date = $(this).text();
            var newdate = new Date(date + " UTC");
            var options = { 
                year: 'numeric', 
                month: 'numeric', 
                day: 'numeric',
                hour: '2-digit',
                minute: '2-digit',
                timeZoneName: 'short'
            }
            $(this).text(newdate.toLocaleString('en-US', options)); 
        }
    })
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM