How do I set the correct date format using moment in strapi v4

System Information
  • v4.xx:
  • Windows 11:
  • Postgres:
  • v16:
  • 8.18:

I want to set an expiration date using moment, but I get an error saying Invalid Date.

The code below worked properly on Strapi v3.

image

I was able to solve the issue.

The issue was that I wasn’t setting the correct format strapi wanted which is the YYYY-MM-DD format. I was able to set the expiration date to 7 days in the future using moment.

Snippet below.

image

Just to giv4e a tip as well :slight_smile: Moment is quite big etc, I would suggest you look into date-fns :slight_smile: Great lib for dates.

1 Like

Yes, I noticed that. Thank you very much for the suggestion, I’ll look into it.

On my front-end (connected to Strapi V4 back-end), I found this solution to display a french date format :

// INPUT
const date = '2023-09-19T12:12:24.261Z';

// FUNCTION
function convertToFrenchDate(date) {
    const dateSubString = date.substring(0, 10) // "2023-09-19"
	const splitDate = dateSubString.split("-") // ["2023", "09", "19"]
	const finalDate = `${splitDate[2]}-${splitDate[1]}-${splitDate[0]}` // "19-09-2023"
  	
  	return finalDate
  }


// OUTPUT
console.log(convertToFrenchDate(date))
// "19-09-2023"

Same way to get the hours :


// INPUT
const date = '2023-09-19T12:12:24.261Z';

// FUNCTION
function convertToFrenchHour(date) {
  const hourSubString = date.substring(11, 19)
  const splitHour = hourSubString.split(':')
  const finalHour = `${splitHour[0]}:${splitHour[1]}:${splitHour[2]}`
  return finalHour
}

// OUTPUT
console.log(convertToFrenchHour(date))
// "12:12:24"