Javascript Date toString convert and format to loc

2020-05-01 09:15发布

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

标签: javascript
3条回答
爷、活的狠高调
2楼-- · 2020-05-01 09:58

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"
查看更多
淡お忘
3楼-- · 2020-05-01 09:59

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)); 
        }
    })
})
查看更多
▲ chillily
4楼-- · 2020-05-01 10:14

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

查看更多
登录 后发表回答