I have an object with property values designating the hours and minutes of a time in military time. I'm trying to have another property that uses a function outside the object to calculate the the time to twelve hour time and hold those values as additional properties.
I have the following code:
$(function () {
console.log( startTime.twelveHourTime );
});
var startTime = {
militaryTime: {
hours: 23,
minutes: 30
},
twelveHourTime: convertToTwelveHourTime (this.militaryTime)
/* I would like this to result in
twelveHourTime: {
hours: 11,
minutes: 30,
amOrpm: 'PM'
}*/
};
function convertToTwelveHourTime (militaryTime) {
var twelveHourTime = {
hours: 0,
minutes: 0,
amOrpm: ''
};
if(militaryTime.hours > 12){
twelveHourTime.hours = militaryTime.hours - 12;
}else{
twelveHourTime.hours = militaryTime.hours;
}
twelveHourTime.minutes = militaryTime.minutes;
if(militaryTime.hours > 11){
twelveHourTime.amOrpm = 'PM';
}else{
twelveHourTime.amOrpm = 'AM';
}
return twelveHourTime;
}
Running this code results in the following errors in the console:
Uncaught TypeError: Cannot read property 'hours' of undefined
referring to the line if(militaryTime.hours > 12)
.
and
Uncaught TypeError: Cannot read property 'twelveHourTime' of undefined
referring to the initial console.log
.
Why is this occurring and how can I fix this code?