Skip to content

Instantly share code, notes, and snippets.

@huttj
Last active August 29, 2015 14:21
Show Gist options
  • Save huttj/6da1f3267022752e24fd to your computer and use it in GitHub Desktop.
Save huttj/6da1f3267022752e24fd to your computer and use it in GitHub Desktop.
Date string parser
function toDate(str) {
// To map months to their numeric equivalent
var months = {
January : 0,
Feburary : 1,
March : 2,
April : 3,
May : 4,
June : 5,
July : 6,
August : 7,
September : 8,
October : 9,
November : 10,
December : 11
};
// Break up the date string with RegEx
// Day, Month, Date, Year, Hour:Minute:Second
var arry = str.match(/(\w+) (\w+) (\d+) (\d{4}) (\d{2}):(\d{2}):(\d{2}).*GMT([+-]\w{4})?/);
// Parse the values as numbers
var month = months[arry[2]];
var date = Number(arry[3]);
var year = Number(arry[4]);
var hour = Number(arry[5]);
var minute = Number(arry[6]);
var second = Number(arry[7]);
// Invert the offset, get as hours
var GMT = Number(arry[8]) / -100;
// Convert everything to equivalent in seconds
var sum = second + (minute*60) + (hour*60*60) + (date*24*60*60) + (monthToDays(month)*24*60*60) + (yearToDays(year)*24*60*60) + (GMT*60*60);
return sum * 1000;
// Helper to get number of days in the year preceding a month
function monthToDays(month) {
var numDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
var days = 0;
for (var i = 0; i < month; i++) {
days += numDays[i];
}
return days;
}
// Helper to get the number of days in years preceding the current year
function yearToDays(year) {
var years = year - 1970;
var days = years * 365;
// Todo: Investigate magic `1`
var leapDays = Math.floor(years / 4) - 1;
return days + leapDays;
}
}
// Test
var dateString = new Date().toString();
var seconds = toDate(dateString);
var calcDate = new Date(seconds).toString();
if (dateString === calcDate) {
console.log('It works!');
} else {
console.log('You found an edge case!', dateString);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment