📜  javascript tolocaletimestring - Javascript (1)

📅  最后修改于: 2023-12-03 14:42:27.486000             🧑  作者: Mango

JavaScript toLocaleTimeString

JavaScript has a built-in function called toLocaleTimeString which allows you to format a JavaScript Date object into a string representation of the time portion of the date.

Syntax
toLocaleTimeString([locales [, options]])
  • locales (optional): A string with a BCP 47 language tag or an array of such strings.
  • options (optional): An object with the following properties:
    • hour12: A Boolean indicating whether to use a 12-hour or 24-hour clock.
    • hour: A string indicating the preferred representation of the hour.
    • minute: A string indicating the preferred representation of the minute.
    • second: A string indicating the preferred representation of the second.
    • timeZoneName: A string indicating the preferred representation of the time zone name.
Return Value

A string representing the time value of the given date according to the locale and formatting options specified.

Example
let date = new Date();
let timeString = date.toLocaleTimeString('en-US', { hour12: true, hour: 'numeric', minute: 'numeric' });
console.log(timeString);
// Output: 3:30 PM
Explanation

The above example uses the toLocaleTimeString function to retrieve the current time as a string with the format hour:minute AM/PM.

The first argument 'en-US' is passed as the locale parameter to obtain the US English time format. The second argument is an object that specifies to use a 12-hour clock (hour12: true), and to only include hour and minute fields in the output.

Conclusion

The toLocaleTimeString function is a powerful tool for formatting UTC or local time as a string in a way that respects the native language and cultural settings of the user. It is important to note that the output format of this function can vary across different browsers and operating systems, so it is often a good idea to test the function thoroughly before deploying it to production.