使用 JavaScript 中提供的标准内置对象 Date 获取系统当前的时间。
【一】
通过分别调用获取年、月、日、时、分、秒、毫秒的方法,然后组合成友好字符串:
var o_date = new Date()
var str_dateTime = o_date.getFullYear()
str_dateTime += "/"
str_dateTime += o_date.getMonth() + 1
str_dateTime += "/"
str_dateTime += o_date.getDate()
str_dateTime += " "
str_dateTime += o_date.getHours()
str_dateTime += ":"
str_dateTime += o_date.getMinutes()
str_dateTime += ":"
str_dateTime += o_date.getSeconds()
str_dateTime += "."
str_dateTime += o_date.getMilliseconds()
其中需要注意 getMonth() 方法获取的月份实际是索引值,也就是从 0 开始的,所以需要单独加一。
【二】
new Date().toLocaleString()
这种方法能够快速获得像这种 2024/7/15 09:24:16 格式的字符串。
【三】
new Date().toString()
这种方法能够快速获得像这种 Mon Jul 15 2024 09:24:33 GMT+0800 (中国标准时间) 格式的字符串。
【四】
new Date().toISOString()
这种方法能够快速获得像这种 2024-07-15T01:40:38.730Z 格式的字符串。
【五】
new Date().toUTCString()
这种方法能够快速获得像这种 Mon, 15 Jul 2024 01:40:47 GMT 格式的字符串。