-1

Is there a know way to convert 10:12am and/or 12:10pm to ISOString format?

So far, I was trying to detect if the the time is an am or pm then remove the last 2 chars. After that im just appending new date string like :

export function timeAMPMToISO(time) {
    var newTime = time.slice(0, -2)
    var isAmPm = time.substr(-2)
    var h = parseInt(newTime.split(':')[0])
    var m = newTime.split(':')[1]
    var date = new Date().toISOString().substring(0, 11);
    if(isAmPm === 'pm'){
        if(h === 12){
            h = h
        }else{
            h += 12
        }
    }
    h = (isAmPm === 'am' && h === 12) ? '00' : h;
    return `${ date }${ h }:${ m }:00.000Z`;
}

I have a feeling that this is not normal.

Is there an existing library for this? MomentJs perhaps? If so, how?

Thanks.

jofftiquez
  • 7,548
  • 10
  • 67
  • 121
  • There are a [*huge number of duplicates*](https://stackoverflow.com/search?q=%5Bjavascript%5D+convert+to+24+hour+time), please do some minimal searching for answers before posting a question. – RobG Jul 04 '17 at 06:25

1 Answers1

1

You can parse your input using moment (String, String) and then use toISOString().

Your code can be like the following:

moment('10:12am', 'hh:mma').toISOString()

The hh token matches 1-12 hours, mm matches 0-59 minutes and a matches am/pm

VincenzoC
  • 30,117
  • 12
  • 90
  • 112