I have string like
Tue Jun 01 2021 09:55:41 GMT+0500 (Pakistan Standard Time)
How I can convert it into date
2021-06-07
I have string like
Tue Jun 01 2021 09:55:41 GMT+0500 (Pakistan Standard Time)
How I can convert it into date
2021-06-07
Convert it into Date object and than into string?
var date = new Date("Tue Jun 01 2021 09:55:41 GMT+0500 (Pakistan Standard Time)");
console.log(date.getFullYear() + "-" + String(date.getMonth() + 1).padStart(2, 0) + "-" + String(date.getDay()).padStart(2, 0));
Date is represented as a standard with timestamp. You can't extract part if date and make its type as date. It would be string only. For formatting there are built in function like Intl. I am attaching here sample as well as link to Init documentation. You can explore more here Intl
var date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0, 200));
options = {
year: 'numeric', month: 'numeric', day: 'numeric',
timeZone: 'America/Los_Angeles'
};
var d= new Intl.DateTimeFormat('en-US', options).format(date);
console.log(d);
Try this,
var date = new Date("Tue Jun 01 2021 09:55:41 GMT+0500 (Pakistan Standard Time)");
const formatDate = date => [
date.getFullYear(),
(date.getMonth() + 1).toString().padStart(2, '0'),
date.getDate().toString().padStart(2, '0')
].join('-');
console.log(formatDate);
The padStart() method pads the current string with another string (multiple times, if needed) until the resulting string reaches the given length. The padding is applied from the start of the current string.
join('-') : adding '-' symbol between every elements(for concatenation)
getMonth()+1 - Since the month starts with 0, 1 is added.
Create Date object from string and then use toISOString()
method to convert it to required format YYYY-mm-dd
.
const convertDate = (dateStr) => {
const myDate = new Date(dateStr)
return myDate.toISOString().split("T")[0];
}
console.log(convertDate("Tue Jun 01 2021 09:55:41 GMT+0500 (Pakistan Standard Time)"));