Home > Back-end >  format date object to string without changing the hour
format date object to string without changing the hour

Time:11-17

So I'm having problem converting my date to this format:

DD/MM/YYYY HH:MM:ss

my front end is retrieving the date from the date stored in the database but somehow when I convert it it's changing the hours. The date is:

2022-11-16T15:00:00.000Z

And I have tried:

const date = moment(date).format("DD/MM/YYYY HH:MM:ss")

it returned:

16/11/2022 12:11:00

How can I achieve just:

16/11/2022 15:00:00

CodePudding user response:

Well one of the mistakes you are making is using HH:MM:ss. The MM is used for months and not for minutes. The correct syntax for this would be HH:mm:ss. See https://momentjs.com/ for reference. This explains why the minutes in your parsed date are wrong.

The hours being wrong could be an issue with the timezone. See here: https://www.alex-arriaga.com/how-to-set-moment-js-timezone-when-creating-a-date/#:~:text=Since Moment.,take the current user's timezone.

I have tried to reproduce this here https://jsfiddle.net/u70po41v/1/

CodePudding user response:

You can use a usual date function

const formatDate = date.toLocaleString()
// => DD/MM/YYYY, HH:MM:ss
  • Related