Home > other >  Moment format returning 'invalid date'
Moment format returning 'invalid date'

Time:11-03

I have the following:

const input: string = '2021-11-2T10:20:00 01:00';

const date: string = moment( input ).format('YYYY-MM-DD');
const time: string = moment( input ).format('HH:mm');

Please can someone tell me why I get 'invalid date' returned for both 'date' and 'time'?

From what I understand the 'input' string is a standard date format (moment gave me this format).

CodePudding user response:

Take care about leading zeros (required by RFC2822/ISO format). You can validate date string using Date constructor:

new Date('2021-11-2T10:20:00 01:00') // Invalid Date (because of date = '2' instead of '02')
new Date('2021-11-02T10:20:00 01:00') // Tue Nov 02 2021 11:20:00 GMT 020 (works fine!)

Same for moment instances:

moment('2021-11-2T10:20:00 01:00') // invalid (error or deprecation warning depends on 'moment' version)
moment('2021-11-02T10:20:00 01:00') // valid

UPD: article about standarts with useful links

CodePudding user response:

What you are using is known as timestamptz. There's an error. So timestamptz is in the following format:

YYYY-MM-DDThh:mm:ssZZ

You are missing a "0" in your day:

2021-11-02T10:20:00 01:00

Then you can just do:

const fullDate = moment('2021-11-02T10:20:00 01:00')
const date = moment( input ).format('YYYY-MM-DD')
const time = moment( input ).format('HH:mm')

Notice i removed : string. You don't need to define the typing btw. It can be infered.

CodePudding user response:

The input string I was using was somehow not valid. When I used "2021-11-02T14:43:59 00:00" it works fine.

  • Related