Search code examples
javascriptdatemomentjsluxon

How to convert string date to specific format?


I am trying to get date from string in specific format like:

    const format = 'MM/dd/yyyy HH:mm';
    const dt = "2021-03-11T22:00:00.000Z"; // expecting "03/11/2021 22:00"
    
    console.log(moment(dt).format(format)); // but getting "03/Th/yyyy 23:00"
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

I tried js date, moment, luxon and I don't understand how to make this :(
I suspect that 000Z made problem but this is date I get.


Solution

  • The difference between Moment.js and Luxon is the case of the format keys. Please review the key/token tables.

    Note: Moment.js has been deprecated in favor of the team's newer library Luxon and other ECMA Script standards that are being introduced in ECMA-402. If you are considering using Moment.js now, just switch over to Luxon.


    If you are using Luxon, you can call .toUTC() right before you format the date. Make sure your day of month (dd) and year (yyyy) format keys are lower-case.

    const DateTime = luxon.DateTime;
    
    const
      format = 'MM/dd/yyyy HH:mm',
      dt = "2021-03-11T22:00:00.000Z";
    
    console.log(DateTime.fromISO(dt).toUTC().toFormat(format)); // 03/11/2021 22:00
    <script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/1.26.0/luxon.min.js"></script>

    If you are using Moment.js, you can call .utc() right before you format the date. Make sure your day of month (DD) and year (YYYY) format keys are upper-case.

    const
      format = 'MM/DD/YYYY HH:mm',
      dt = "2021-03-11T22:00:00.000Z";
    
    console.log(moment(dt).utc().format(format)); // 03/11/2021 22:00
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>