BST date string to javascript date

2019-03-01 06:44发布

How can I convert the BST date string to Javascript date object?

The follwing code gives me error for BST but works for other timezone

var data='Tue Apr 28 16:15:22 BST 2015';
var date = new Date(data);
console.log(date)

Output

Invalid Date

var data='Tue Apr 28 16:15:22 BST 2015';
var date = new Date(data);
console.log(date)

var data2='Fri Mar 27 11:53:50 GMT 2015'
var date2 = new Date(data2);
console.log(date2)

1条回答
Fickle 薄情
2楼-- · 2019-03-01 07:36
  1. Don't rely on Date to know timezone names
  2. Don't mix a date with a time; the year should be before the time, the timezone should be the very last thing

Putting these together

var timezone_map = {
    'BST': 'GMT+0100'
};

function re_order(str) {
    var re = /^(\w+) (\w+) (\d\d) (\d\d:\d\d:\d\d) (\w+) (\d\d\d\d)$/;
    return str.replace(re, function ($0, day, month, date, time, zone, year) {
        return day + ' ' + month + ' ' + date + ' ' + year + ' ' + time + ' ' + (timezone_map[zone] || zone);
    });
}

new Date(re_order('Tue Apr 28 16:15:22 BST 2015'));
// Tue Apr 28 2015 16:15:22 GMT+0100 (GMT Daylight Time)
查看更多
登录 后发表回答