Skip to content

Instantly share code, notes, and snippets.

@yblee85
Created May 8, 2014 16:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yblee85/de21b9530376048ae491 to your computer and use it in GitHub Desktop.
Save yblee85/de21b9530376048ae491 to your computer and use it in GitHub Desktop.
JavaScript DateConvert AM PM to Military and Miltity to AM PM
function getDateObjectFromTimeOnlyPart(default_date, timeString) {
// default_date : date object, timeString format "11:00" or "03:00 pm"
var time = new Date(default_date);
var hhmm = undefined;
var ampm = undefined;
if(_.str.contains(timeString.toLowerCase(), "m")) {
// am/pm format ex) 04:00 am
var timeStringArray = timeString.split(" ");
hhmm = (timeStringArray[0]).split(':');
ampm = timeStringArray[1].toLowerCase();
if(ampm == "am" && hhmm[0]=="12") {
hhmm[0] = "00";
}
} else {
hhmm = timeString.split(':');
}
time.setHours(Number(hhmm[0]) + ((!_.isUndefined(ampm) && ampm == "pm" && Number(hhmm[0])!=12)?12:0));
time.setMinutes(Number(hhmm[1]));
time.setSeconds(0);
return time;
}
function getAMPMFormatTimeFromString(strTime) {
// ex) 13:00
if(_.str.contains(strTime.toLowerCase(), "M")) {
return strTime;
} else {
var hhmm = strTime.split(":");
var now = new Date();
now.setHours(Number(hhmm[0]));
now.setMinutes(Number(hhmm[1]));
return now.toString("hh:mm tt").toUpperCase();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment