Expand my Community achievements bar.

Guidelines for the Responsible Use of Generative AI in the Experience Cloud Community.
SOLVED

Formatting a date field auto populated with Javascript

Avatar

Level 2

I have a date field, which I auto-populate to be the current days date with the following code:

var date=new Date();

var month=date.getMonth()+1;

this.rawValue=month+"/"+date.getDate()+"/"+(date.getYear()-100);

This works fine, but it comes out as 7/20/12 instead of 07/20/2012 like my pattern defines.

Whether or not I write my code to be the correct format, I always get an "Invalid format" error. How can I fix this?

1 Accepted Solution

Avatar

Correct answer by
Level 2

The solutions is to format the date in YYYY-MM-DD when setting the raw value.

var date=new Date();
var month=date.getMonth()+1;

var day=date.getDate();

if(month<10){ month="0"+month; }

if(day<10) {day="0"+day; }
this.rawValue=date.getFullYear()+"-"+month+"-"+day;

View solution in original post

1 Reply

Avatar

Correct answer by
Level 2

The solutions is to format the date in YYYY-MM-DD when setting the raw value.

var date=new Date();
var month=date.getMonth()+1;

var day=date.getDate();

if(month<10){ month="0"+month; }

if(day<10) {day="0"+day; }
this.rawValue=date.getFullYear()+"-"+month+"-"+day;