Search code examples
datetimetimezonemomentjsdate-formatmoment-timezone

How can i fix timezone issue while using date format in moment.js?


This is my input date , let inputDate = '2021-01-15T11:22:10.000Z'. I want to change the date format to MM/DD/YYYY HH:mm:ss For that i used following i used moment.js . This is my code,

moment(inputDate).format('MM/DD/YYYY HH:mm:ss') = 01/15/2021 16:52:10

After formatting the date i am getting the date with timezone added.How can i get the exact time in MM/DD/YYYY HH:mm:ss format ?

I tried the following as well;

moment(inputDate).local(true).format('MM/DD/YYYY HH:mm:ss')
moment(inputDate).utcOffset(330).format('MM/DD/YYYY HH:mm:ss')
moment(inputDate).utcOffset(0).format('MM/DD/YYYY HH:mm:ss')
moment(inputDate).utcOffset("+05:30").format('MM/DD/YYYY HH:mm:ss')
moment(inputDate).utcOffset("-05:30").format('MM/DD/YYYY HH:mm:ss')

Please help me to figure out the issue .


Solution

  • You should tell moment that the date you provide is in UTC. You can achieve this by using utc() function:

    moment.utc(inputDate)
    

    If you format after utc(), you will see the date in UTC timezone:

    moment.utc(inputDate).format('MM/DD/YYYY HH:mm:ss')
    

    let inputDate = '2021-01-15T11:22:10.000Z';
    
    console.log(moment.utc(inputDate).format('MM/DD/YYYY HH:mm:ss'));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>