Rowie Po
Rowie Po

Reputation: 1419

convert 12-hour hh:mm AM/PM to 24-hour hh:mm

Is there any simple way to convert 12-hour hh:mm AM/PM to 24-hour hh:mm using jquery?

Note: not using any other libraries.

I have a var time = $("#starttime").val() that returns a hh:mm AM/PM.

Upvotes: 86

Views: 253914

Answers (30)

Harsh Patel
Harsh Patel

Reputation: 1344

/**
 * Combines a date string with a time string (either in 12-hour AM/PM format or 24-hour format)
 * to produce a `Date` object representing the specified date and time.
 *
 * This function takes a date string in the format "YYYY-MM-DD" and a time string which can be either
 * in "HH:MM AM/PM" format (12-hour clock) or "HH:MM" format (24-hour clock). It returns a `Date` object 
 * that combines both. The seconds and milliseconds are set to zero.
 *
 * @param {string} dateString - A string representing the date in "YYYY-MM-DD" format. The date string must be a valid date.
 * @param {string} timeString - A string representing the time in either "HH:MM AM/PM" (12-hour) or "HH:MM" (24-hour) format.
 * @returns {Date} - A `Date` object representing the combined date and time. The time is set according to the provided time string,
 *                    and the date is set according to the provided date string.
 * @throws {Error} - Throws an error if the provided time string is invalid or if the provided date string is invalid.
 *
 * @example
 * const dateString = '2024-08-12';
 * const timeString = '12:00 PM'; // or '23:59' for 24-hour format
 * const result = combineDateAndTimeString(dateString, timeString);
 * console.log(result); // Logs: Date object representing August 12, 2024, 12:00 PM or 23:59 depending on input
 */
class DateTimeUtils {
    static combineDateAndTimeString(dateString, timeString) {
        // Parse the time string to create a base Date object
        const baseDate = new Date(`1/1/2013 ${timeString}`);
        if (isNaN(baseDate.getTime())) {
            throw new Error('Invalid time format. Ensure the time string is in "HH:MM AM/PM" or "HH:MM" format.');
        }

        // Parse the provided date string
        const parsedDate = Date.parse(dateString);
        if (isNaN(parsedDate)) {
            throw new Error('Invalid date format. Ensure the date string is in a valid format like "YYYY-MM-DD".');
        }

        // Create a new Date object from the parsed date string
        const finalDateTime = new Date(parsedDate);
        // Set the time from the baseDate object onto the finalDateTime object
        finalDateTime.setHours(baseDate.getHours());
        finalDateTime.setMinutes(baseDate.getMinutes());
        finalDateTime.setSeconds(0);
        finalDateTime.setMilliseconds(0);

        return finalDateTime;
    }
}

// Example usage
const dateString = '2024-08-12';
const timeString = '12:00 PM'; // or '23:59' for 24-hour format
const result = DateTimeUtils.combineDateAndTimeString(dateString, timeString);
console.log(result); // Logs: Date object representing August 12, 2024, 12:00 PM or 23:59 depending on input

Upvotes: 0

Jefrey Bulla
Jefrey Bulla

Reputation: 191

Following these rules:

from 01:00:00AM to 11:59:59AM -> remove AM/PM
from 12:00:00PM to 12:59:59PM -> remove AM/PM
from 01:00:00PM to 11:59:59PM -> add 12 to the HH and remove AM/PM
from 12:00:00AM to 12:59:59AM -> change HH to 00 

Assuming a string input such as: 12:05:45AM

The following function will output the string: 00:05:45

function timeConversion(s){
    const sCopy = s.slice()    
    const n = s.length
    const hours = parseInt(s.slice(0,2))
    const dayNight = s.slice(8,10)

    if(hours >= 1 && hours <= 11 && dayNight == 'AM' ){
        return s.slice(0,n-2)
    }
    if(hours == 12 && dayNight == 'PM' ){
        return s.slice(0,n-2)
    }
    if(hours >= 1 && hours <= 11 && dayNight == 'PM'){
        const newHour = hours + 12
        const sModified = sCopy.slice(2,n-2)  // remove hour and AM/PM
        return newHour + sModified
    }
    if(hours == 12 && dayNight == 'AM'){
        const newHour = '00'
        const sModified = sCopy.slice(2,n-2) // remove hour and AM/PM
        return newHour + sModified
    }

Upvotes: 0

Fawaz Ahmed
Fawaz Ahmed

Reputation: 1594

const to24Hours = value => new Date(`2024-06-15 ${value}`).toLocaleString("sv-SE", { timeStyle:'short' })

console.log(to24Hours('08:12 PM'))

Upvotes: 0

Chris Dąbrowski
Chris Dąbrowski

Reputation: 1992

This question needs a newer answer :)

const convertTime12to24 = (time12h) => {
  const [time, modifier] = time12h.split(' ');

  let [hours, minutes] = time.split(':');

  if (hours === '12') {
    hours = '00';
  }

  if (modifier === 'PM') {
    hours = parseInt(hours, 10) + 12;
  }

  return `${hours}:${minutes}`;
}

console.log(convertTime12to24('12:00 AM'));
console.log(convertTime12to24('12:59 AM'));
console.log(convertTime12to24('12:00 PM'));
console.log(convertTime12to24('12:59 PM'));
console.log(convertTime12to24('01:02 PM'));
console.log(convertTime12to24('05:06 PM'));

Upvotes: 97

Suresh B
Suresh B

Reputation: 427

To convert a time from 12-hour format to 24-hour format using Moment.js in jQuery

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>

<script>
  $(document).ready(function() {
    const time12 = '02:30 PM'; // Replace this with your 12-hour time string
    const time24 = moment(time12, 'hh:mm A').format('HH:mm');
    console.log(time24);
  });
</script>

Replace '02:30 PM' in the code with your desired 12-hour time string. When you run this script, it will output the converted time in the 24-hour format.

Remember to include jQuery and the Moment.js library in your HTML file before running this code. You can include jQuery similarly to how you include the Moment.js

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>

Upvotes: 3

Avraham Weinstein
Avraham Weinstein

Reputation: 894

EDIT: This answer does not handle seconds

Here is my solution, using regex to split. Simple and short:

convert24To12(time){
    let [hours, minutes, modifier] = time.split(/ |:/);
    if (modifier === 'PM') {
        hours = `${parseInt(hours, 10) + 12}`;      
    }
    time = `${hours}:${minutes}`;
    return time;
}

Upvotes: -2

kasongoyo
kasongoyo

Reputation: 1876

An extended version of @krzysztof answer with the ability to work on time that has space or not between time and modifier, can use uppercase and lowercase for the modifier.

function convertTime12to24(time12h) {
    let [hours, minutes, modifier] = time12h.match(/(\d+|pm|am)/gi);

    if (hours === '12') {
        hours = '00';
    }

    if (modifier.toLowerCase() === 'pm') {
        hours = parseInt(hours, 10) + 12;
    }

    return `${hours}:${minutes}`;
}

console.log(convertTime12to24('12:00 PM'));
console.log(convertTime12to24('12:00 pm'));
console.log(convertTime12to24('12:00pm'));
console.log(convertTime12to24('12:00 AM'));
console.log(convertTime12to24('12:00 am'));
console.log(convertTime12to24('12:00am'));

Upvotes: 6

djangonaut
djangonaut

Reputation: 7778

Here my solution including seconds:

function convert_to_24h(time_str) {
    // Convert a string like 10:05:23 PM to 24h format, returns like [22,5,23]
    var time = time_str.match(/(\d+):(\d+):(\d+) (\w)/);
    var hours = Number(time[1]);
    var minutes = Number(time[2]);
    var seconds = Number(time[3]);
    var meridian = time[4].toLowerCase();

    if (meridian == 'p' && hours < 12) {
      hours += 12;
    }
    else if (meridian == 'a' && hours == 12) {
      hours -= 12;
    }
    return [hours, minutes, seconds];
  };

Upvotes: 12

Renat Gatin
Renat Gatin

Reputation: 6396

Here is TypeScript solution. Remark it ignores seconds.

/**
 * Safe parsing of american 12-hour time (ex.: 4:45 PM) to ISO-8601 24-hour time (such as 16:45:00).
 * This method ignores seconds
 *
 * @param dateStr - american 12-hour time
 * @private
 */
export const parseAmericanTimeToIso = (timeStr: string): string => {
  if (timeStr) {
    try {
      const [time, modifier] = timeStr.split(' ');
      const [hourStr, minute] = time.split(':');
      const hour = parseInt(hourStr) + (modifier === 'PM' ? 12 : 0);
      return `${hour}:${minute}:00`;
    } catch (e) {
      console.error('Error parsing 12-hour to ISO-8601 24-hour time: ', timeStr);
      return null;
    }
  }
  return null;
};

console.log(parseAmericanTimeToIso("10:45 PM"); // 22:45:00

Upvotes: 0

Rakesh Mishra
Rakesh Mishra

Reputation: 1

var time = "9:09:59AM"
var pmCheck = time.includes("PM");
var hrs = parseInt(time.split(":")[0]);
var newtime = '';
// this is for between  12 AM to 12:59:59AM  = 00:00:00
if (hrs == 12 && pmCheck == false) {
    newtime = "00" + ':' + time.split(":")[1] + ':' + time.split(":")[2].replace("AM", '');
}
//this is for between  12 PM to 12:59:59 =12:00:00
else if (hrs == 12 && pmCheck == true) {
    newtime = "12" + ':' + time.split(":")[1] + ':' + time.split(":")[2].replace("PM", '');
}
//this is for between 1 AM and 11:59:59 AM
else if (!pmCheck) {
    newtime = hrs + ':' + time.split(":")[1] + ':' + time.split(":")[2].replace("AM", '');
}
//this is for between 1 PM and 11:59:59 PM
else if (pmCheck) {
    newtime = (hrs + 12) + ':' + time.split(":")[1] + ':' + time.split(":")[2].replace("PM", '');
}
console.log(newtime);

Upvotes: 0

Caleb C. Adainoo
Caleb C. Adainoo

Reputation: 97

HackerRank TimeConversion Solution

12-hour AM/PM format, to military (24-hour) time

function timeConversion(s) {
    let time = 0
    let hour = s.slice(0, 2)
    let toD = s.slice(-2)

    if (toD === 'AM' && hour == 12) {
        time = `00${s.slice(2, s.length -2)}`
    } else {
        if (toD === 'PM' && hour < 12) {
            time = `${Number(12 + parseInt(hour))}${s.slice(2, s.length - 2)}`
        } else {
            time = s.slice(0, s.length - 2)
        }
    }

    return console.log(time)
}

timeConversion('12:00:17AM') // 00:00:17
timeConversion('09:21:33PM') // 21:21:33
timeConversion('12:43:53PM') // 12:43:53

Upvotes: 1

Axiom_shuvo
Axiom_shuvo

Reputation: 73

I'm adding a simple code -

const time = '12:10AM';

function convertTo24HrsFormat(time) {
    let [hour, modifier] = time.split(":");
    let min = parseInt(modifier).toString().padStart(2, '0');
    let index = modifier.toLowerCase().indexOf('m');
    let meridian = modifier.slice(index - 1);
    hour = parseInt(hour);

    if (hour === 12) {
        hour = 00;
    }

    if (meridian == 'PM') {
        hour = hour + 12;
    }

    hour = hour.toString().padStart(2, '0');


    let time24hr = `${hour}:${min}`;

    return time24hr;
}

console.log(`Converted time: ${convertTo24HrsFormat(time)}`);

Upvotes: 0

Maria
Maria

Reputation: 3525

In case you're looking for a solution that converts ANY FORMAT to 24 hours HH:MM correctly.

function get24hTime(str) {
    str = String(str).toLowerCase().replace(/\s/g, '');
    var has_am = str.indexOf('am') >= 0;
    var has_pm = str.indexOf('pm') >= 0;
    // first strip off the am/pm, leave it either hour or hour:minute
    str = str.replace('am', '').replace('pm', '');
    // if hour, convert to hour:00
    if (str.indexOf(':') < 0) str = str + ':00';
    // now it's hour:minute
    // we add am/pm back if striped out before 
    if (has_am) str += ' am';
    if (has_pm) str += ' pm';
    // now its either hour:minute, or hour:minute am/pm
    // put it in a date object, it will convert to 24 hours format for us 
    var d = new Date("1/1/2011 " + str);
    // make hours and minutes double digits
    var doubleDigits = function(n) {
        return (parseInt(n) < 10) ? "0" + n : String(n);
    };
    return doubleDigits(d.getHours()) + ':' + doubleDigits(d.getMinutes());
}

console.log(get24hTime('6')); // 06:00
console.log(get24hTime('6am')); // 06:00
console.log(get24hTime('6pm')); // 18:00
console.log(get24hTime('6:11pm')); // 18:11
console.log(get24hTime('6:11')); // 06:11
console.log(get24hTime('18')); // 18:00
console.log(get24hTime('18:11')); // 18:11

Upvotes: 3

RobG
RobG

Reputation: 147513

Because all the answers so far seem to be verbose, here's a simple minimalist solution:

/* Convert h:mm a/p to H:mm
 * i.e. 12 hour time to 24 hour time
 * @param {string} time - h:mm a/p format
 * @returns {string} time in H:mm format
 */
function to24HrTime(time) {
  let [hr, min, ap] = time.toLowerCase().match(/\d+|[a-z]+/g) || [];
  return `${(hr % 12) + (ap == 'am'? 0 : 12)}:${min}`;
}

['9:02 am',
 '9:02 pm',
 '9:02am',
 '9:02pm',
 '12:15 AM',
 '12:01 PM',
].forEach(time => console.log(`${time} -> ${to24HrTime(time)}`));

That assumes the input string has a suitable format and values. A more robust version is:

/* Given 12 hr time, return24 hr time
 * @param {string} time - time in format h:mm am/pm
 *        h  must be in range 1 to 12
 *        mm must be in range 00 to 59
 *        am/pm is not case sensitive
 * @returns {string} time in 24 hr format H:mm
 *        H  in range 0 to 23
 *        mm in range 00 to 59
 *
 */
function to24HrTime(time = new Date().toLocaleString('en',{hour:'numeric', minute:'2-digit', hour12:true})) {
  let [hr, min, ap] = String(time).toLowerCase().match(/\d+|[a-z]+/g) || [];
  // If time is valid, return reformatted time
  // Otherwise return undefined
  return /^([1-9]|1[0-2]):[0-5]\d\s?(am|pm)/i.test(time)? `${(hr%12)+(ap=='am'?0:12)}:${min}` : void 0;
}

// Examples
// Without arguments
console.log(`No args -> ${to24HrTime()}`);
// Valid input
['9:02 am',
 '9:02 pm',
 '9:02am',
 '9:02pm',
 '12:15 AM',
 '12:01 PM',
 // Invalid input
 '12',       // Missing mins & ap
 '99:05 am', // hrs out of range
 '0:05 am',  // hrs out of range
 '9:60 am',  // mins out of range
 '9:09 pp',  // ap out of range
 {},         // Random object
].forEach(time => console.log(`${time} -> ${to24HrTime(time)}`));

Upvotes: 3

Vishwajeet Mishra
Vishwajeet Mishra

Reputation: 446

//here is my solution.
function timeConversion(s) {
        // Write your code here
        let amPM = s.indexOf('AM') !== -1 ? 'AM' : 'PM';
        let tString = s.toString().replace(/AM|PM/gi,'');
        let splitTime = tString.split(':');
        let h = splitTime[0];
        let m = splitTime[1];
        let sec = splitTime[2];
        let twntyfr = amPM === 'PM' && parseInt(h) !== 12 ? parseInt(h)+12 : h;
        if(parseInt(twntyfr) === 12 && amPM === 'AM') twntyfr = '00';
        return twntyfr+':'+m+':'+sec;
    }

Upvotes: 1

Michael
Michael

Reputation: 445

A well tested approach:

// example, s = 12:34:56PM
function timeConversion(s) {
    let designator, clock, hhmmss, hh, mm, ss, mil; // declare variables
    designator = s.slice(-2); // returns AM or PM
    hhmmss = s.substring(0, s.length-2) // returns hh:mm:ss
    clock = hhmmss.split(':'); // returns array of [hh,mm,ss]
    hh = designator === 'AM' 
       ? (parseInt(clock[0]) === 12 ? '00' : clock[0]) 
       : (parseInt(clock[0]) === 12 ? '12' : parseInt(clock[0]) + 12);
    mm = clock[1];
    ss = clock[2];
    mil = [hh,mm,ss].join(':').toString();
    return mil

}

Upvotes: 0

Muhammad Ahmed Hassan
Muhammad Ahmed Hassan

Reputation: 539

function timeConversion(amPmStr = '') {
    const time = amPmStr.replace(/(AM|PM|am|pm)/, (match) => ' ' + match);
    const randomDate = "September 25, 2018 ";
    const date = new Date(randomDate + time);
    const hours = date.getHours().toString().padStart(2, '0');
    const mins = date.getMinutes().toString().padStart(2, '0');
    const secs = date.getSeconds().toString().padStart(2, '0');
    return hours + ":" + mins + ":" + secs;
}

Upvotes: 0

Rabindra Kumar Mahato
Rabindra Kumar Mahato

Reputation: 99

Here is brute force kind of solution which works for me

const time = '11:8AM';

function convertTo24HrsFormat(time) {
    // write your solution here
    let timeWithPM = time.endsWith("PM");
    
    if (time.includes('P')) {
        let minuteVal = time.slice(time.indexOf(':')+1, time.indexOf('P'));
      
      if(minuteVal.length === 1) {
        minuteVal = `0${minuteVal}`;
        let result = time.slice(0, time.indexOf(':'));
        time = `${result}:${minuteVal}PM`;
        console.log("CHECKING123====>>>>", time);
      }
    } 
    
    if (time.includes('A')) {
        let minuteVal = time.slice(time.indexOf(':')+1, time.indexOf('A'));
      if(minuteVal.length === 1) {
        minuteVal = `0${minuteVal}`;
        let result = time.slice(0, time.indexOf(':'));
        time = `${result}:${minuteVal}AM`;
      }
    } 
        

    if(timeWithPM) {
        let result = findHour(time);
        return result;
    }

    if(!timeWithPM) {
        let result = withAM(time);
        return result;
    }

    return;
}

function findHour(time) {
    let hour = time.slice(0, time.indexOf(':'));
    if(parseInt(hour) < 12)
        hour = parseInt(hour)+12;
    if (hour.toString().length === 1)
        hour = `0${hour}`;
    let removeHourWithPM = time.split(":").pop();
    removeHourWithPM = `${hour}:${removeHourWithPM}`;
    // console.log("CHECKING-----",hour);
    return removeHourWithPM.slice(0, -2);
}

function withAM(time) {

        let isTwelve = time.slice(0, time.indexOf(':'));
    if(isTwelve == '12') {
        let get12 = time.split(':').pop();
        let result = get12.slice(0, -2);
        return `00:${result}`
    }
    
        let hour = time.slice(0, time.indexOf(':'));
    if(hour.length === 1) {
        hour = `0${hour}`;
      let removeHourWithSingledigit = time.split(":").pop();
      removeHourWithSingledigit = `${hour}:${removeHourWithSingledigit}`;
      return removeHourWithSingledigit.slice(0, -2);
    }
    
    return time.slice(0, -2);
}

console.log(`Converted time: ${convertTo24HrsFormat(time)}`)

Upvotes: 0

ZowWeb
ZowWeb

Reputation: 139

I found this to be the simplest way. Here's a step-by-step on what's happening:

  1. You get the time in 12-hour format

  2. Split the time by timestamp & meridian

  3. If it's midnight, prepend 00 otherwise print just the timestamp

  4. If it's noon, just print the timestamp otherwise add the hour with 12

function timeConversion(s) {
    // 07:05:45PM
    const timeInAmPmArray = s.split(/(AM|PM)/) // ['07:05:45', 'PM', '']
    const hour = Number(timeInAmPmArray[0].split(':')[0]) // 7
    const amOrPm = timeInAmPmArray[1] // PM
    let timeIn24Hour = ''
    if(amOrPm === 'AM') {
      timeIn24Hour = hour === 12 ? `00:${timeInAmPmArray[0].split(':').slice(1).join(':')}` : timeInAmPmArray[0]
    } else {
      timeIn24Hour = hour === 12 ? timeInAmPmArray[0] : `${hour + 12}:${timeInAmPmArray[0].split(':').slice(1).join(':')}`
      // timeIn24Hour = 19:05:45
    }
    return timeIn24Hour
}
    
timeConversion('07:05:45PM')

Upvotes: 0

morteza
morteza

Reputation: 738

that is how i implement this :

function timeConversion(s) {
    // Write your code here
   const arr =s.split(":")
   const isAM = arr[2].includes("AM")
   if(isAM) {
      arr[0]=arr[0].padStart(2, '0');
      arr[2]=arr[2].replace("AM","");  
        if(arr[0]==="12")  arr[0] ="00"
           
    }else{
        arr[0]=(+arr[0]+12).toString();
        arr[2]=arr[2].replace("PM","");  
        if(arr[0]==="24")  arr[0] ="12"
    }
   return(arr.join(":"))
}

Upvotes: 0

Vinodh Ram
Vinodh Ram

Reputation: 809

Converting AM/PM Time string to 24 Hours Format. Example 9:30 PM to 21:30

function get24HrsFrmAMPM(timeStr) {
    if (timeStr && timeStr.indexOf(' ') !== -1 && timeStr.indexOf(':') !== -1) {
        var hrs = 0;
        var tempAry = timeStr.split(' ');
        var hrsMinAry = tempAry[0].split(':');
        hrs = parseInt(hrsMinAry[0], 10);
        if ((tempAry[1] == 'AM' || tempAry[1] == 'am') && hrs == 12) {
            hrs = 0;
        } else if ((tempAry[1] == 'PM' || tempAry[1] == 'pm') && hrs != 12) {
            hrs += 12;
        }
        return ('0' + hrs).slice(-2) + ':' + ('0' + parseInt(hrsMinAry[1], 10)).slice(-2);
    } else {
        return null;
    }
}

Upvotes: 1

Jomin George Paul
Jomin George Paul

Reputation: 569

function formatto24(date) {
  let ampm = date.split(" ")[1];
  let time = date.split(" ")[0];
  if (ampm == "PM") {
    let hours = time.split(":")[0];
    let minutes = time.split(":")[1];
    let seconds = time.split(":")[2];
    let hours24 = JSON.parse(hours) + 12;
    return hours24 + ":" + minutes + ":" + seconds;
  } else {
    return time;
  }
}

Upvotes: 0

Eddy Vinck
Eddy Vinck

Reputation: 450

I just solved this issue on HackerRank, so I'm here to share my result

function timeConversion(s) {
    const isPM = s.indexOf('PM') !== -1;
    let [hours, minutes, seconds] = s.replace(isPM ? 'PM':'AM', '').split(':');

    if (isPM) {
        hours = parseInt(hours, 10) + 12;
        hours = hours === 24 ? 12 : hours;
    } else {
        hours = parseInt(hours, 10);
        hours = hours === 12 ? 0 : hours;
        if (String(hours).length === 1) hours = '0' + hours;
    }

    const time = [hours, minutes, seconds].join(':');

    return time;
}

This works for inputs like 06:40:03AM.

Upvotes: 0

Danil Valov
Danil Valov

Reputation: 663

Short ES6 code

const convertFrom12To24Format = (time12) => {
  const [sHours, minutes, period] = time12.match(/([0-9]{1,2}):([0-9]{2}) (AM|PM)/).slice(1);
  const PM = period === 'PM';
  const hours = (+sHours % 12) + (PM ? 12 : 0);

  return `${('0' + hours).slice(-2)}:${minutes}`;
}
const convertFrom24To12Format = (time24) => {
  const [sHours, minutes] = time24.match(/([0-9]{1,2}):([0-9]{2})/).slice(1);
  const period = +sHours < 12 ? 'AM' : 'PM';
  const hours = +sHours % 12 || 12;

  return `${hours}:${minutes} ${period}`;
}

Upvotes: 0

Muneeb
Muneeb

Reputation: 1559

Tested for all the use cases

function timeConversion(s) {
let h24;
let m24;
let sec24;

const splittedDate = s.split(":");
const h = parseInt(splittedDate[0], 10);
const m = parseInt(splittedDate[1], 10);
const sec = parseInt(splittedDate[2][0] + splittedDate[2][1], 10); 
const meridiem = splittedDate[2][2] + splittedDate[2][3];

if (meridiem === "AM") {
    if (h === 12) {
        h24 = '00';
    } else {
        h24 = h;
        if (h24 < 10) {
            h24 = '0' + h24;
        }
    }
    m24 = m;
    sec24 = sec;
} else if (meridiem === "PM") {
    if (h === 12) {
        h24 = h
    } else {
        h24 = h + 12;
        if (h24 < 10) {
            h24 = '0' + h24;
        }
    }
    m24 = m;
    sec24 = sec;
}


if (m24 < 10) {
    m24 = '0' + m24; 
} 

if (sec24 < 10) {
    sec24 = '0' + sec24;
}

  return h24 + ":" + m24 + ":" + sec24; 
}

Here is the jsfiddle working example

Upvotes: 0

rynop
rynop

Reputation: 53689

Typescript solution based off of @krzysztof-dąbrowski 's answer

export interface HoursMinutes {
  hours: number;
  minutes: number;
}
export function convert12to24(time12h: string): HoursMinutes {
  const [time, modifier] = time12h.split(' ');
  let [hours, minutes] = time.split(':');

  if (hours === '12') {
    hours = '00';
  }

  if (minutes.length === 1) {
    minutes = `0${minutes}`;
  }

  if (modifier.toUpperCase() === 'PM') {
    hours = parseInt(hours, 10) + 12 + '';
  }

  return {
    hours: parseInt(hours, 10),
    minutes: parseInt(minutes, 10)
  };
}

Upvotes: 0

Robert Ni&#241;o
Robert Ni&#241;o

Reputation: 21

single and easy js function for calc time meridian in real time

JS

   function convertTime24to12(time24h) {
                var timex = time24h.split(':');

                if(timex[0] !== undefined && timex [1] !== undefined)
                 {
                     var hor = parseInt(timex[0]) > 12 ? (parseInt(timex[0])-12) : timex[0] ;
                     var minu = timex[1];
                     var merid = parseInt(timex[0]) < 12 ? 'AM' : 'PM';

                     var res = hor+':'+minu+' '+merid;

                     document.getElementById('timeMeridian').innerHTML=res.toString();
                 }
            }

Html

 <label for="end-time">Hour <i id="timeMeridian"></i> </label>
            <input type="time" name="hora" placeholder="Hora" id="end-time" class="form-control" onkeyup="convertTime24to12(this.value)">

Upvotes: 0

Andrew
Andrew

Reputation: 528

For anybody reading this in the future, here is a simpler answer:

var s = "11:41:02PM";
var time = s.match(/\d{2}/g);
if (time[0] === "12") time[0] = "00";
if (s.indexOf("PM") > -1) time[0] = parseInt(time[0])+12;
return time.join(":");

Upvotes: 3

Dexter Adams
Dexter Adams

Reputation: 524

I've created a bit of an adaptation of script @devnull69 submitted. I felt for my application it would be more useful as a function that returned the value that I could, then use as a variable.

HTML

<input type="text" id="time_field" />
<button>Submit</submit>

jQuery

$(document).ready(function() {

    function convertTime(time) {

        var hours = Number(time.match(/^(\d\d?)/)[1]);
        var minutes = Number(time.match(/:(\d\d?)/)[1]);
        var AMPM = time.match(/\s(AM|PM)$/i)[1];

        if((AMPM == 'PM' || AMPM == 'pm') && hours < 12) {
            hours = hours + 12;
        }
        else if((AMPM == 'AM' || AMPM == "am") && hours == 12) {
            hours = hours - 12;
        }

        var sHours = hours.toString();
        var sMinutes = minutes.toString();

        if(hours < 10) {
            sHours = "0" + sHours;
        }
        else if(minutes < 10) {
             sMinutes = "0" + sMinutes;
        }

        return sHours + ":" + sMinutes;

    }

    $('button').click(function() {
        alert(convertTime($('#time_field').val()));
    });

});

Upvotes: 0

Ismael Terreno
Ismael Terreno

Reputation: 1131

With this you can have the following: Sample Input: 07:05:45PM Sample Output: 19:05:45

function timeConversion(s) {
    let output = '';
    const timeSeparator = ':'
    const timeTokenType = s.substr(s.length - 2 , 2).toLowerCase();
    const timeArr = s.split(timeSeparator).map((timeToken) => {
    const isTimeTokenType = 
          timeToken.toLowerCase().indexOf('am') > 0 ||                                                                                               
           timeToken.toLowerCase().indexOf('pm');
        if(isTimeTokenType){
            return timeToken.substr(0, 2);
        } else {
            return timeToken;
        }
    });
    const hour = timeArr[0];
    const minutes = timeArr[1];
    const seconds = timeArr[2];
    const hourIn24 = (timeTokenType === 'am') ? parseInt(hour) - 12 : 
    parseInt(hour) + 12;
    return hourIn24.toString()+ timeSeparator + minutes + timeSeparator + seconds;
}

Hope you like it !

Upvotes: 2

Related Questions