user1250264
user1250264

Reputation: 905

Javascript Moment.js Change time from AM to PM

I am trying to add 12:00 PM to an existing Moment date object. In debugging, the date object looks like this

Tues Sept 01 2019 00:00:00 GMT-0400

I am convert to a string but getting the AM after the conversion.

MyDate = moment(this.TestDate.format("MM/DD/YYYY h:mm A");

I read the moment.js docs and thought that adding the 'A' would change the AM to PM but so far it does not work. I read a few post and tried a few different version of code but so far no luck.

I would like to get the following date string after the conversion

10/10/2019 12:00 PM

Thanks

Upvotes: 0

Views: 804

Answers (1)

sebastienbarbier
sebastienbarbier

Reputation: 6832

Adding 'A' in format() only display 'AM'/'PM'. You need to first manipulate your date and then display the new value.

Assuming this.TestDate is a moment instance :

MyDate = moment(this.TestDate.add('12', 'hours').format("MM/DD/YYYY h:mm A");

About manipulation

Be careful about moment's manipulation, it change the moment instance inside your variable, meaning :

MyDate = moment('Tues Sept 01 2019 00:00:00 GMT-0400')
console.log(Mydate); // Show Tues Sept 01 2019 00:00:00 GMT-0400
MyDate2 = MyDate.add(12, 'hours');
console.log(Mydate); // Show Tues Sept 01 2019 12:00:00 GMT-0400

Upvotes: 2

Related Questions