一、JS代码
<script>
document.write((new Date().getTimezoneOffset())/60 + '<br>');//返回本地时间和UTC的时差
document.write(+ new Date() + '<br>');//+new Date()==new Date().valueof()==new Date().getTime()==Date.now()
document.write(Date.now() + '<br>');//返回当前时间的毫秒数
document.write(new Date().toUTCString() + '<br>');//返回UTC时间的字符串Fri: 07 Dec 2018 06:13:38 GMT
document.write(new Date().toLocaleString() + '<br>');//返回本地时间的字符串:2018/12/7 下午2:13:38
document.write(new Date().toDateString() + '<br>');//返回本地日期的字符串:Fri Dec 07 2018
document.write(new Date().toTimeString() + '<br>');//返回中国标准时间:14:13:38 GMT+0800 (中国标准时间)
document.write(Date.parse('May 25 ,2004')+ '<br>');
document.write(Date.parse('5 25 ,2004')+ '<br>');
document.write(Date.parse('5/25/2004')+ '<br>');
document.write(Date.parse('2004-05-25')+ '<br>');
document.write(Date.parse('2004,05-25')+ '<br>');
document.write(Date.parse('2004,05,25')+ '<br>');
document.write(Date.parse('2004/05/25')+ '<br>');
/*Date.parse():接收一个表示日期的字符串,返回相应日期的毫秒数
Date.parse('2004-05-25'):使用'-'做连接符时,返回的UTC时间的毫秒数
*/
</script>
二、示例
//获取并格式化日期:年-月-日
<script>
function formate(time) {
return time.getFullYear() + '-' + time.getMonth() + '-' + time.getDay();
}
document.write(formate(new Date()) + '<br>');
//字符串转换为日期,字符串格式:2011-11-20
function convertToDate(strings) {
return new Date(Date.parse(strings.replace(/-/g, "/")));
}
document.write(convertToDate('2011-11-20'));
</script>
本文深入讲解JavaScript中日期和时间的处理方法,包括获取本地和UTC时间的时差、格式化日期、将字符串转换为日期等实用技巧。通过具体示例,帮助读者掌握JS日期对象的各种方法,如toUTCString、toLocaleString、toDateString、toTimeString及Date.parse的用法。
1705

被折叠的 条评论
为什么被折叠?



