Convert 12 hour (AM/PM) string to 24 Date object using moment js

后端 未结 8 1059
轻奢々
轻奢々 2021-02-01 01:26

I have a output resulting from a timepicker giving 12 hour format of time.

Eg : \"1:45 AM (or) \"12:15 PM\" as **string**

Is there a way to par

8条回答
  •  生来不讨喜
    2021-02-01 01:32

    Here's how you can set the time of a Date object using a time String.

    const date = new Date('1/1/21');
    const pm = '2:30 PM';
    const am = '11:00 AM';
    const noon = '12:00 PM';
    const midnight = '12:00 AM';
    
    const mergeDateTime = (date, time) => {
      const parsedTime = moment(time, ['h:mm A']);
      const merged = moment(date).set({
        hours: parsedTime.get('hours'),
        minutes: parsedTime.get('minutes')
      });
      
      return merged.toDate();
    };
    
    const resultsList = document.querySelector('#results');
    
    const inputs = [pm, am, noon, midnight];
    
    inputs.forEach((input) => {
      const li = document.createElement('li');
      li.innerText = `${input} ➡ ${mergeDateTime(date, input)}`;
      resultsList.appendChild(li);
    });
    
    
    

    Results

提交回复
热议问题