下面是一个例子 日期:toLocaleString() 方法
- 例子:
<
script
>
var d = new Date(Date.UTC(2020, 9, 26, 7, 0, 0));
var result = d.toLocaleString();
document.write("Date and Time of apocalypse: "
+ result);
</
script
>
- 输出:
Date and Time of apocalypse: 26/10/2020, 12:30:00
这个 日期toLocaleString() 方法用于将日期和时间转换为字符串。 语法:
dateObj.toLocaleString(locales, options)
参数: 该方法接受两个参数,如下所述:
- 地区: 此参数是包含一个或多个语言或区域设置标记的区域设置字符串数组。请注意,它是一个可选参数。如果要在应用程序中使用特定的语言格式,请在locales参数中指定该语言。
- 选项: 它也是一个可选参数,包含指定比较选项的属性。一些属性包括localeMatcher、timeZone、weekday、year、month、day、hour、minute、second等。
返回值: 它以字符串值的形式返回日期和时间,格式由语言环境指定。
注: 这个 dateObj 应该是有效的日期对象。
项目1: 此代码打印当前日期和时间。还有,在这个代码中 toLocaleString() 方法不使用任何参数,因此它使用操作系统的区域设置约定并返回特定于机器的结果。
<
script
>
var d = new Date();
var result = d.toLocaleString();
document.write("date and time as a string = " + result);
</
script
>
输出:
date and time as a string = 6/26/2018, 10:28:17
项目2: 这段代码以locale参数指定的字符串格式打印日期和时间。
<
script
>
var date = new Date(Date.UTC(2018, 5, 26, 7, 0, 0));
var options = { hour12: false };
document.write(date.toLocaleString("en-US"));
document.write("<
br
>");
document.write(date.toLocaleString("en-US", options));
</
script
>
输出:
6/26/2018, 12:30:00 PM 6/26/2018, 12:30:00
注: 这个 toLocaleString() 方法不同于 toLocaleDateString() 像 toLocaleDateString() 仅将日期对象的日期转换为字符串,但 toLocaleString() 将日期和时间转换为字符串。。
支持的浏览器: 支持的浏览器 JavaScript Date toLocaleString()方法 以下列出了:
- 谷歌Chrome 1及以上版本
- 边缘12及以上
- Firefox 1及以上版本
- Internet Explorer 3及以上版本
- 歌剧3及以上
- Safari 1及以上