Is it possible that the method of moment format does not work well?

1

I find myself with the following, I have to format some dates and I always used the moments. Now I have this dilemma:

var date2 = new Date(year, 6, 0);
var dateEnd = formatShortDate(date2.toString());

and the method formatShortDate , which is the following:

export function formatShortDate(date: string, originalFormat: string = "", finalFormat: string = "DD/MM/YYYY"): string {
 var possibleInputFormats = [
    'YYYY-MM-DD[T]HH:mm:ss',
    'DD/MM/YYYY',
    'DD/MM/YYYY HH:mm:ss.mmm',
    'MMMM Do YYYY, H:m:s a',
    'x',
    'DDMMYYYY',
    'YYYY-MM-DDTHH:mm:ss',
]

if (date) {
    var momentObj = moment(date, possibleInputFormats);
    if (!momentObj.isValid()) {
        momentObj = getMomentValid(date);
    }
    return momentObj.format(finalFormat);
}
else {
    return '';
}

This always returns on 30/1/2017, why could it be?

    
asked by Pekée 03.04.2017 в 11:10
source

2 answers

2

The problem is that the method .toString() of the object Date returns the date in a format not included in your array possibleInputFormats .

Example:

new Date(2017, 6, 0).toString();
// "Fri Jun 30 2017 00:00:00 GMT-0300 (Local Standard Time)"

One solution would be:

  • Use the .toISOString method of the object Date .

  • Add the format ISO to the array possibleInputFormats .

Example:

var possibleInputFormats = [
  'YYYY-MM-DD[T]HH:mm:ss',
  'DD/MM/YYYY',
  'DD/MM/YYYY HH:mm:ss.mmm',
  'MMMM Do YYYY, H:m:s a',
  'x',
  'DDMMYYYY',
  'YYYY-MM-DDTHH:mm:ss',
  moment.ISO_8601 // Agregamos el formato ISO
];
var date = new Date(2017, 6, 0); // 30/06/2017

// Utilizamos el metodo "toISOString()"
console.log(moment(date.toISOString(), possibleInputFormats).format('DD/MM/YYYY'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
    
answered by 03.04.2017 / 14:53
source
0

What happened was that you put day 0:

var date2 = new Date(year, 6, 0);

Days start at 1, months at 0 years at 1. It should be done like this:

var date2 = new Date(year, month-1, day);
    
answered by 03.04.2017 в 14:46