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.
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.
Share Improve this question asked Feb 7, 2022 at 6:15 ganesh kaspateganesh kaspate 2,69512 gold badges52 silver badges105 bronze badges3 Answers
Reset to default 3The native Date object es 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);
You could use the methods shown in this blogpost https://bobbyhadz./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)')));
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}
;