I have a date string in the format 28-Dec-2016 04:25 AM
and need to convert it to a Date
object. For this, I first split the string to get the date and time
cDateStringParts = cdate.split(' ');
Then I get the date and time components
cDateParts = cDateStringParts[0].split('-');
cTimeParts = cDateStringParts[1].split(':');
Then I initialize the Date
object like
if(cDateStringParts[2]=='AM'){
cDateObject = new Date(cDateParts[2], convertToNumericMonth(cDateParts[1]), cDateParts[0], cTimeParts[0], cTimeParts[1], 0, 0);
} else {
cDateObject = new Date(cDateParts[2], convertToNumericMonth(cDateParts[1]), cDateParts[0], complaintTimeParts[0] + 12, cTimeParts[1], 0, 0);
}
where convertToNumericMonth()
is a function which converts Jan-Dec to 0-11.But I do not get the correct values when I check cDateObject.getDate()/getMonth()/getYear()
. The result is 2017/12/29.
What am I doing wrong? If I try to do alert(cdate,' ',cDateObject.getFullYear()
I get this:
One issue is how 12hr time is converted to 24hr time. The date parts are strings, so for "03:45 PM" the following:
complaintTimeParts[0] + 12
will return "0312". Also, "12:00 AM" should have the hours set to 0, but your code will set the hours to 12.
The hours can be converted to 24hr time by converting to a number first, converting 12am to 0 and then adding 12 if it's PM. Also simpler if done separately from the rest of the calculation:
var hr = cTimeParts[0] % 12 + (cDateStringParts[2]=='AM'? 0 : 12);
Here the mod operator %
will convert cTimeParts[0]
to a number. Now the function can be:
function dateParse(cdate) {
var cDateStringParts = cdate.split(' ');
var cDateParts = cDateStringParts[0].split('-');
var cTimeParts = cDateStringParts[1].split(':');
var hr = cTimeParts[0] % 12 + (cDateStringParts[2]=='AM'? 0 : 12);
return new Date(cDateParts[2], convertToNumericMonth(cDateParts[1]),
cDateParts[0], hr, cTimeParts[1]);
}
function convertToNumericMonth(month) {
return {Jan:0,Feb:1,Mar:2,Apr:3,May:4,Jun:5,Jul:6,
Aug:7,Sep:8,Oct:9,Nov:10,Dec:11}[month];
}
console.log(dateParse('28-Dec-2016 04:25 AM').toString());
console.log(dateParse('28-Dec-2016 04:25 PM').toString());
Lastly, missing parts are set to 0 (or 1 for the date) so they don't need to be included.