Context:
Hi, I am trying to generate a moment.js format
from the given start time and end time.
let sourceTime = { "startTime": "0600", // 6 AM "endTime": "2100" // 9 PM }
Using the above endTime property I am trying to get time in the format below :
2021-02-04T09:00 pm i.e This format https://momentjs.com/docs/#/displaying/format/ – “YYYY-MM-DDThh:mm a”
using this piece of code
let currentDate = moment().format('DD-MM-YYYY'); let savedFormat = moment(`${currentDate} ${sourceTime.endTime.substring(0, 2)}:${sourceTime.endTime.substring(2, 4)}`).format('YYYY-MM-DDThh:mm')
Where I am adding the current date and end time in a customized way using a string literal to generate the desired format.
Problem:
I am getting 9:00 am instead of 9:00 pm.
2021-02-04T09:00 am
Not sure where I’m doing wrong. Any suggestion would be helpful.
let sourceTime = { "startTime": "0600", // 6 AM "endTime": "2100" // 9 PM } let currentDate = moment().format('DD-MM-YYYY'); let savedFormat = moment(`${currentDate} ${sourceTime.endTime.substring(0, 2)}:${sourceTime.endTime.substring(2, 4)}`).format('YYYY-MM-DDThh:mm') console.log(savedFormat); //Shows am instead of pm console.log(moment(savedFormat).format('YYYY-MM-DDThh:mm a')); //OUTPUT
<script src="https://momentjs.com/downloads/moment.min.js"></script>
Advertisement
Answer
After consulting Momentjs Format, I would propose the following solution:
let sourceTime = { "startTime": "0600", // 6 AM "endTime": "2100" // 9 PM } const startTime = moment(sourceTime.startTime, 'HHmm').format('YYYY-MM-DD h:mm a'); const endTime = moment(sourceTime.endTime, 'HHmm').format('YYYY-MM-DD h:mm a'); console.log(startTime + ' to ' + endTime);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>