JavaScript格式化时间与日期

1. Date 对象方法

toLocaleString() 根据本地时间格式,把 Date 对象转换为字符串。  "2018/10/8 上午8:00:00"
toLocaleTimeString() 根据本地时间格式,把 Date 对象的时间部分转换为字符串。 "上午8:00:00"
toLocaleDateString() 根据本地时间格式,把 Date 对象的日期部分转换为字符串。  "2018/10/8"
new Date('2018-10-08').toLocaleTimeString()
// "上午8:00:00"

new Date('2018-10-08').toLocaleDateString()
// "2018/10/8"

new Date('2018-10-08').toLocaleString()
// "2018/10/8 上午8:00:00"

 注意点:

(1)该方法存在兼容性问题,不同的浏览器以及浏览器不同版本下获得的格式可能不同(部分可能为2018-10-08,而非2018/10/08)

(2)unix时间戳是秒(10位的数字),而js转化new Date()的时候使用的是毫秒,需要*1000

2. moment.js 类库格式化时间日期

moment.js 是一个JavaScript 日期处理类库,支持日期时间格式化、相对时间、日历时间和多语言支持。

格式化示例: 

moment().format('MMMM Do YYYY, h:mm:ss a'); // 十月 8日 2018, 2:21:57 下午
moment().format('dddd');                    // 星期一
moment().format("MMM Do YY");               // 10月 8日 18
moment().format('YYYY [escaped] YYYY');     // 2018 escaped 2018
moment().format();                          // 2018-10-08T14:21:57+08:00

猜你喜欢

转载自blog.csdn.net/xiaomajia029/article/details/82967111
今日推荐