I need to convert a string in this format MM/yyyy
to a Date()
object in Angular.
I'm getting an Invalid Date
error while doing: new Date('01/2020')
How do I instantiate a Date object using this specific format?
I need to convert a string in this format MM/yyyy
to a Date()
object in Angular.
I'm getting an Invalid Date
error while doing: new Date('01/2020')
How do I instantiate a Date object using this specific format?
You are passing a month and year without a day. The Date object needs the day also for constructing the date. A valid date is consists of day, month and year.
Pass the day also:
new Date('01/01/2020')
If you do not want to pass the day:
const str = '01/2020';
const year = str.substr(3,6);
const month = str.substr(0,2);
new Date(year, month - 1)
You need substr
method to select year and month from your string. The month starts from zero. If 01 is January for you then you need to substruct 1 from the month.
You can just parse the string and use this Date constructor:
const year = 2020;
const month = 2; // March
const date = new Date(year, month);
// Constructors:
new Date();
new Date(value);
new Date(dateString);
new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]);