Change date format

How to change the format of new Date() from 24 hrs to normal…for example I want that the current Date I should get as 1:12:34 instead of 13:12:34

Well, you can’t change the format of the actual Date object that new Date() returns. But I assume you mean as a string.

toLocaleString gives you the string, you pass a locale code as the first argument, then whatever options you want in the second. If you want to use the default locale that your system thinks it is in (I assume you do), then you can set the locale string to undefined and pass an object:

const myDate = new Date();
myDate.toLocaleString(undefined, {hour12: true});

Note that some locales ('en-US' for example) should default to 12hr representation, it’s culture dependent.

Example (assuming it’s the afternoon where I am rather than being 11AM). The match is just a regex to pull the time part out of the date string.

> const myDate = new Date();
> myDate.toLocaleString(undefined, {hour12: true}).match(/\d{1,2}:\d\d:\d\d [AP]M/)[0]
'3:04:53 PM'
1 Like