Home > Blockchain >  Moment and date-fns formatting date incorrect
Moment and date-fns formatting date incorrect

Time:01-26

I have been trying to format a zulu format date to normal date i.e. MM/dd/yyyy, so far I have tried date-fns and moment. The date I have is 2022-11-03T19:48:24Z I am expecting it to be formatted as 11/03/2022 but I am getting 11/04/2022, I do not understand why it is adding a day to the date and how can I fix this ?

export function fDate(
  date: Date | string | number,
  template: string = 'MM/dd/yyyy'
) {
  return format(new Date(date), template);
}
fDate('2022-11-03T19:48:24Z')

expected outcome 11/03/2022 but getting 11/04/2022

format is coming from date-fns

CodePudding user response:

Do not use the Date constructor to parse a date_time string when you are using a library like moment.js or date-fns. Instead, use the applicable constructor or methods in the library you want to use.

moment.js

The symbols posted in your question do not match the required symbols. The symbols, d and D have different meanings. The same is the case with y and Y. Check the documentation page at https://momentjs.com/docs/

The following code produces the correct result as 11/03/2022.

var moment = require('moment');  

console.log(moment("2022-11-03T19:48:24Z").format('MM/DD/YYYY'));

In your code, this will be implemented as

return moment(date).format('MM/DD/YYYY');

date-fns

The symbols posted in your question match the required symbols.

The following code produces the correct result as 11/03/2022.

const fns = require('date-fns')

console.log(fns.format(fns.parseISO('2022-11-03T19:48:24Z'), 'MM/dd/yyyy'))

In your code, this will be implemented as

return fns.format(fns.parseISO(date), 'MM/dd/yyyy');

CodePudding user response:

Using moment's parseZone helped me

export function fDateISOStringToDate(
  date: string,
  template: string = "MM/DD/YYYY"
) {

  return moment.parseZone(date).format(template);
}
  • Related