Context:
Hi, I am trying to generate a moment.js format
from the given start time and end time.
JavaScript
x
5
1
let sourceTime = {
2
"startTime": "0600", // 6 AM
3
"endTime": "2100" // 9 PM
4
}
5
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
JavaScript
1
3
1
let currentDate = moment().format('DD-MM-YYYY');
2
let savedFormat = moment(`${currentDate} ${sourceTime.endTime.substring(0, 2)}:${sourceTime.endTime.substring(2, 4)}`).format('YYYY-MM-DDThh:mm')
3
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.
JavaScript
1
13
13
1
let sourceTime = {
2
"startTime": "0600", // 6 AM
3
"endTime": "2100" // 9 PM
4
}
5
6
let currentDate = moment().format('DD-MM-YYYY');
7
let savedFormat = moment(`${currentDate} ${sourceTime.endTime.substring(0, 2)}:${sourceTime.endTime.substring(2, 4)}`).format('YYYY-MM-DDThh:mm')
8
9
console.log(savedFormat);
10
11
//Shows am instead of pm
12
console.log(moment(savedFormat).format('YYYY-MM-DDThh:mm a'));
13
//OUTPUT
JavaScript
1
1
1
<script src="https://momentjs.com/downloads/moment.min.js"></script>
Advertisement
Answer
After consulting Momentjs Format, I would propose the following solution:
JavaScript
1
8
1
let sourceTime = {
2
"startTime": "0600", // 6 AM
3
"endTime": "2100" // 9 PM
4
}
5
const startTime = moment(sourceTime.startTime, 'HHmm').format('YYYY-MM-DD h:mm a');
6
const endTime = moment(sourceTime.endTime, 'HHmm').format('YYYY-MM-DD h:mm a');
7
8
console.log(startTime + ' to ' + endTime);
JavaScript
1
1
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>