📅  最后修改于: 2023-12-03 15:20:39.760000             🧑  作者: Mango
toLocaleTimeString(short)
in JavaScriptThe toLocaleTimeString(short)
is a JavaScript method that returns a localized string representing the time portion of a Date object, formatted according to the specified options. It allows developers to display the time in a short format according to the locale of the user's browser.
dateObj.toLocaleTimeString(locale, options)
locale
(optional): A string with a BCP 47 language tag, or an array of such strings. If you don't provide this parameter, the user's browser locale will be used.
options
(optional): An object with one or more of the following properties:
hour12
(default is true
): A Boolean value that indicates whether the hour is represented in 12-hour or 24-hour format.
hourCycle
(default is h11
): A string that indicates whether ISO 8601's 'h23', 'h24', or 'h11' should be used.
timeZone
(default is undefined
): A string with a time zone identifier, such as 'UTC' or 'America/Los_Angeles', or a custom time zone abbreviation, such as 'GMT-8'.
const now = new Date();
const timeString = now.toLocaleTimeString('default', { hour12: false });
console.log(timeString);
Output:
18:23:01
const now = new Date();
const options = { hour12: true };
const timeString = now.toLocaleTimeString('fr-FR', options);
console.log(timeString);
Output:
21:34:56
const now = new Date();
const options = { timeZone: 'America/Los_Angeles' };
const timeString = now.toLocaleTimeString('default', options);
console.log(timeString);
Output:
2:23:45 PM
toLocaleTimeString(short)
is a flexible and easy-to-use method for displaying localized time in a web application. With just a few lines of code, you can display the time in the user's preferred format, language, and time zone.