Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to return the "time" portion of the Date as a string using the current locale's conventions?
To return the "time" portion of the Date as a string, using the current locale's conventions, use the toLocaleTimeString() method.
The toLocaleTimeString() method relies on the underlying operating system in formatting dates. It converts the date to a string using the formatting convention of the operating system where the script is running. For example, in the United States, the time appears in 12-hour format with AM/PM, whereas in many European countries, it appears in 24-hour format.
Syntax
date.toLocaleTimeString([locales], [options])
Parameters
- locales (optional): A string or array of strings representing locale identifiers (e.g., 'en-US', 'de-DE')
- options (optional): An object with formatting options like hour12, timeZone, etc.
Basic Example
You can try to run the following code to return the "time" portion of the Date as a string:
<html>
<head>
<title>JavaScript toLocaleTimeString Method</title>
</head>
<body>
<script>
var dt = new Date(2018, 0, 15, 14, 16, 30);
document.write("Formatted Date - Time: " + dt.toLocaleTimeString());
</script>
</body>
</html>
Formatted Date - Time: 2:16:30 PM
Using Different Locales
<html>
<body>
<script>
var dt = new Date(2018, 0, 15, 14, 16, 30);
document.write("US Format: " + dt.toLocaleTimeString('en-US') + "<br>");
document.write("German Format: " + dt.toLocaleTimeString('de-DE') + "<br>");
document.write("Japanese Format: " + dt.toLocaleTimeString('ja-JP') + "<br>");
</script>
</body>
</html>
US Format: 2:16:30 PM German Format: 14:16:30 Japanese Format: 14:16:30
Using Options
<html>
<body>
<script>
var dt = new Date(2018, 0, 15, 14, 16, 30);
// Force 24-hour format
var options24 = { hour12: false };
document.write("24-hour format: " + dt.toLocaleTimeString('en-US', options24) + "<br>");
// Show only hours and minutes
var optionsHM = { hour: '2-digit', minute: '2-digit' };
document.write("Hours and minutes: " + dt.toLocaleTimeString('en-US', optionsHM) + "<br>");
</script>
</body>
</html>
24-hour format: 14:16:30 Hours and minutes: 02:16 PM
Comparison of Time Formats
| Locale | Time Format | Example Output |
|---|---|---|
| en-US | 12-hour with AM/PM | 2:16:30 PM |
| de-DE | 24-hour format | 14:16:30 |
| ja-JP | 24-hour format | 14:16:30 |
Conclusion
The toLocaleTimeString() method provides flexible time formatting based on locale conventions. Use locale parameters and options to customize the output format according to your requirements.
