I am using react-calendar , Here I am getting a date in the following format
Wed Feb 02 2022 00:00:00 GMT 0530 (India Standard Time)
Now I am trying to convert it to dd/mm/yyyy. is there any way though which I can do this ?
Thanks.
CodePudding user response:
You could use the methods shown in this blogpost https://bobbyhadz.com/blog/javascript-format-date-dd-mm-yyyy from Borislav Hadzhiev.
You could a new date based on your calendar date and afterwards format it:
function padTo2Digits(num) {
return num.toString().padStart(2, '0');
}
function formatDate(date) {
return [
padTo2Digits(date.getDate()),
padTo2Digits(date.getMonth() 1),
date.getFullYear(),
].join('/');
}
console.log(formatDate(new Date('Wed Feb 02 2022 00:00:00 GMT 0530 (India Standard Time)')));
CodePudding user response:
The native Date object comes with seven formatting methods. Each of these seven methods give you a specific value -
toString(): Fri Jul 02 2021 14:03:54 GMT 0100 (British Summer Time)toDateString(): Fri Jul 02 2021toLocaleString(): 7/2/2021, 2:05:07 PMtoLocaleDateString(): 7/2/2021toGMTString(): Fri, 02 Jul 2021 13:06:02 GMTtoUTCString(): Fri, 02 Jul 2021 13:06:28 GMTtoISOString(): 2021-07-02T13:06:53.422Z
var date = new Date();
// toString()
console.log(date.toString());
// toDateString()
console.log(date.toDateString());
// toLocalString()
console.log(date.toLocaleString());
// toLocalDateString()
console.log(date.toLocaleDateString());
// toGMTString()
console.log(date.toGMTString());
// toGMTString()
console.log(date.toUTCString());
// toGMTString()
console.log(date.toISOString());
Format Indian Standard time to Local time -
const IndianDate = 'Wed Feb 02 2022 00:00:00 GMT 0530 (India Standard Time)';
const localDate = new Date(IndianDate).toLocaleDateString();
console.log(localDate);
CodePudding user response:
This is JavaScript default date format.
You can use libraries like momentjs, datefns, etc to get the result.
For example, if you are using momentjs:-
moment(date).format('dd/mm/yyyy);
Or if you don't want to use any third-party library you can get the result from JavaScript's default date object methods.
const date = new Date();
const day = date.getDate() < 10 ? 0${date.getDate()} : date.getDate();
const month = date.getMonth() 1 < 10 ? 0${date.getMonth() 1} : date.getDate() 1;
const year = date.getFullYear();
const formattedDate = ${day}/${month}/${year};
