Date manipulation: Difference between revisions
Content added Content deleted
(Nimrod -> Nim) |
|||
Line 818: | Line 818: | ||
<lang JavaScript>function add12hours(dateString) { |
<lang JavaScript>function add12hours(dateString) { |
||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
var months = ['January','February','March','April','May','June', |
var months = ['January','February','March','April','May','June', |
||
'July','August','September','October','November','December']; |
'July','August','September','October','November','December']; |
||
var zones = {'EST': 300, 'AEST': -600}; // Minutes to add to zone time to get UTC |
var zones = {'EST': 300, 'AEST': -600}; // Minutes to add to zone time to get UTC |
||
// Convert month name to number, zero indexed |
// Convert month name to number, zero indexed. Return if invalid month |
||
month = months.indexOf(month); |
|||
// Could use indexOf but not supported widely |
|||
if (month === -1) { return; } |
|||
for (var i=0, iLen=months.length; i<iLen; i++) { |
|||
if (months[i] == month) { |
|||
month = i; |
|||
} |
|||
⚫ | |||
if (typeof month != 'number') return; // Invalid month name provided |
|||
// |
// Add 12 hours as specified. Add another 12 if pm for 24hr time |
||
hr += (ampm.toLowerCase() === 'pm') ? 24 : 12 |
|||
hr += 12; |
|||
} |
|||
// Add 12 hours to hours |
|||
hr += 12; |
|||
// Create a date object in local zone |
// Create a date object in local zone |
||
var |
var localTime = new Date(year, month, date); |
||
localTime.setHours(hr, min, 0, 0); |
|||
⚫ | |||
⚫ | |||
⚫ | |||
// d is now a local date representing the same moment as the |
|||
// source date plus 12 hours |
// representing the same moment as the source date plus 12 hours |
||
⚫ | |||
return |
return localTime; |
||
} |
} |
||
var inputDateString = 'March 7 2009 7:30pm EST'; |
var inputDateString = 'March 7 2009 7:30pm EST'; |
||
console.log( |
|||
alert( |
|||
'Input: ' + inputDateString + '\n' + |
'Input: ' + inputDateString + '\n' + |
||
'+12hrs in local time: ' + add12hours(inputDateString) |
'+12hrs in local time: ' + add12hours(inputDateString) |