JavaScript获取系统时间字符串,并格式化
在JavaScript中,获取当前时间并转换为字符串格式可以通过多种方式实现。以下是一些常用的方法:
1. 使用Date对象和toString()方法
let now = new Date();
let nowStr = now.toString(); // 默认返回格式为:Wed Jun 15 2023 10:47:30 GMT+0800 (China Standard Time)
console.log(nowStr);
2. 使用toLocaleString()方法
toLocaleString()可以根据本地环境将日期转换为字符串,但它返回的格式可能因地区而异。
let now = new Date();
let nowStr = now.toLocaleString(); // 返回格式可能类似于:2023/6/15 上午10:47:30
console.log(nowStr);
3. 使用toISOString()方法
如果你需要ISO 8601扩展格式的日期字符串(即YYYY-MM-DDTHH:mm:ss.sssZ),则可以使用toISOString()。
let now = new Date();
let nowStr = now.toISOString(); // 返回类似:2023-06-15T02:47:30.000Z
console.log(nowStr);</