1

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)
NullPointerException
  • 3,732
  • 5
  • 28
  • 62
  • By _BST_ I assume you mean _GMT+1_ ? Also, why is your time between your day and year? – Paul S. Apr 29 '15 at 16:04
  • It looks like you're relying on the browser specific date string parsing - i had a similar issue a while ago. If nobody else beat me to it I'll post when I get into work. – Krease Apr 29 '15 at 16:05
  • 1
    Related: [this](http://stackoverflow.com/questions/2587345/javascript-date-parse), and [this](http://stackoverflow.com/questions/19797608/parsing-iso8601-like-date-in-javascript-new-date-doesnt-work-across-browsers). Also check out [this](http://dygraphs.com/date-formats.html) chart showing issues with Javascript parsing dates from strings compatibility across browsers. In general, I recommend steering away from the default Date(String) constructor and go with a library or different constructor. – Krease Apr 29 '15 at 17:13

1 Answers1

2
  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)
Paul S.
  • 64,864
  • 9
  • 122
  • 138