Day.js unable to properly format date input in nodejs and reactjs

Viewed 23

I am trying to implement dayjs package in my node.js application. I would like my date and time to be formatted like this:

2022-09-11T17:46:00+01:00

I have my codes like this:

const dayjs = require("dayjs");
const utc = require("dayjs/plugin/utc");
const customParseFormat = require('dayjs/plugin/customParseFormat');
const dayJsUTC = dayjs.extend(utc)
const dayJsDate = dayJsUTC.extend(customParseFormat)

I am trying to check that the format comes out this way 2022-09-11T17:46:00+01:00 Here is the code:

  if(!dayJsDate( 2022-09-11T17:46:00+01:00, "YYYY-MM-DD HH:mm", true).isValid()){
            return res.status(500).json('invalid date')
        }

It is returning invalid date. I know I am not doing it properly. How can I do it properly to scale this validation?

Also, if I want to simply create only date, hour and minute without the additional time details, how can I do that using dayjs?

1 Answers

Sorry for not answering your question straight, but you could get what you want by defining your own function. When you pass no args to it, it returns just time in format like you wish, when passing a string to function - it return true or false, checking format. If you pass second param as "true", function will return date, hours and minutes.

const myDate = (input, noSecondsAndOffset) => {
   const
      offset = -(new Date().getTimezoneOffset()),
      offsetHours = '0' + offset / 60,
      offsetMins = '' + offset % 60,
      timeZone = `${offsetHours}:${offsetMins}${offsetMins.length === 1 ? '0' : ''}`,
      currTime = `${new Date().toJSON().slice(0, -5)}+${timeZone}`,
      checker = (string) => !!string.match(/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\+\d{2}:\d{2}/);
   return typeof input === 'string'
      ? checker(string)
      : !noSecondsAndOffset
         ? currTime
         : currTime.slice(0, -9)
}
Related