简体   繁体   中英

Javascript 12 Hour to 24 Format convertor

Is there any way i could convert a 12hour time format into a 24 hour format in JS? I'm not that good with JavaScript at all so still surprised i could manage to get even this far.

What i'm trying to do is convert time from 12 hour to 24 hour so i can do comparison, like if endDate is greater than startDate, but what i cant understand is how to convert the 12 hour format i receive to a valid 24hour format.

$('#de_endTime').bind('blur', function()
{
    sDate = $('#de_startDate').val();
    startTime = $('#de_startTime').val();
    endTime = $('#de_endTime').val();

    if (startTime == ""){
        alert("First input the start time");
        $('#de_startTime').focus();
    }

    dSplit = sDate.split("-");
    dYear = dSplit[0];
    dMonth = dSplit[1] - 1;
    dDay = dSplit[2];

    stSplit = startTime.split(":");
    stHour = stSplit[0];
    stMin = stSplit[1].split(" ")[0];
    stAmPm = stSplit[1].split(" ")[1];

    etSplit = endTime.split(":");
    etHour = etSplit[0];
    etMin = etSplit[1].split(" ")[0];
    etAmPm = etSplit[1].split(" ")[1];

    fullStartDate = getDateObject(dYear, dMonth, dDay, stHour, stMin);
    fullEndDate = getDateObject(dYear, dMonth, dDay, etHour, etMin);

    if (fullStartDate - fullEndDate > 0){
        alert("Start Time cannot be higher than End Time!");
    }
});

Here is the getDateObject() function

function getDateObject(year, month, day, hours, minutes) {
  var newDate = new Date();
  newDate.setFullYear(year);
  newDate.setMonth(month);
  newDate.setDate(day);

  newDate.setHours(hours);
  newDate.setMinutes(minutes);
  newDate.setSeconds(0);
  newDate.setMilliseconds(0);
  return newDate;
}

I'm not sure if i've provided enough detail, but please let me know if didnt :) Thanks :)

[ EDIT ] The new code, which seems to be outputting everything fine so far :)

$('#de_endTime').bind('blur', function()
{
    sDate = $('#de_startDate').val();
    startTime = $('#de_startTime').val();
    endTime = $('#de_endTime').val();

    if (startTime == ""){
        alert("First input the start time");
        $('#de_startTime').focus();
    }

    dSplit = sDate.split("-");
    dYear = dSplit[0];
    dMonth = dSplit[1];
    dDay = dSplit[2];

    fullIsoDate = dMonth + "/" + dDay + "/" + dYear;
    //alert(fullIsoDate);

    var fullStartDate = new Date(startTime + ' ' + fullIsoDate);
    var fullEndDate = new Date(endTime + ' ' + fullIsoDate);

    alert(fullStartDate);
    if (fullStartDate - fullEndDate > 0){
        alert("Start Time cannot be higher than End Time!");
    }
    alert(fullEndDate > fullStartDate)
});

date objects can be compared directly, and do not care about 12/24 hour format, so just put your times in two date objects and compare.

var dateOne = new Date('1:00 PM 1/1/1900');
var dateTwo = new Date('13:01 1/1/1900');

if(dateOne < dateTwo)
{
    alert('DateOne is before DateTwo');
} else {
    alert('DateOne is after DateTwo');
}

You will get a alert box that says DateOne is before DateTwo

I had been looking everywhere for just something SIMPLE to convert a time from 24-hour format to 12, or vice versa. Literally everything out there was only dealing with dates, or time and dates. So I made a simple time convertor and figured it anyone else needs one here it is (based off of the first example's split methods).

//usage timeConvert("12:01 PM","24")  results  12:01:00
//OR    timeConvert("12:01:00","12")  results  12:01 PM
function timeConvert(time,twelvOrTwen){ 
    var stSplit = time.split(":");
    var stHour = stSplit[0];
    var stMin = stSplit[1].split(" ")[0];
    var stAmPm = stSplit[1].split(" ")[1];
    var newhr = 0;
    var ampm = '';
    var newtime = '';
   // alert("hour:"+stHour+"\nmin:"+stMin+"\nampm:"+stAmPm); //see current values
    if (twelvOrTwen == "12") {
        if (stHour == 12){
        ampm = "PM";
        newhr = 12;
        }
        else if (stHour == 00){;
        ampm = "AM";
        newmin = stMin;
        newhr = 12;
        }
        else if (stHour > 12){
        newhr = stHour - 12;
        ampm = "PM";
        }
        else {
        newhr = stHour;
        ampm = "AM";
        }
        newtime = newhr+":"+stMin+" "+ampm;
    }
    else if (twelvOrTwen == "24"){
    if ((stAmPm == "pm") || (stAmPm == "PM")){ 
        if (stHour < 12) {
        newhr = (stHour*1)+(1*12); //goes to 13
        }
        else { //means is 12:30 PM
        newhr = 12;
        }
    }
    newtime = newhr+":"+stMin+":"+"00";
    }
    else {
    alert("No Time To Convert Or Didn't Specify 12 or 24");
    }
    return newtime;
}

Apparently, this question is already old, but I would be pasting my solution to answer the question that your title states. However this must mean that the 12 hour time format must come with a space separating the time and time of the day ie ( am or pm ).

Solution 1:

function convertTimeTo24(time) {
    const realTime = time.split(" ");
    if (realTime[1].toLowerCase() === "am") {
        return realTime[0];
    } else {
        const timeToReturn = realTime[0].split(":");
        const increaseHours = Number(timeToReturn[0]) + 12;

        return `${increaseHours}:${timeToReturn[1]}`;
    }
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM