javaScript系列:js中獲取時間new Date()詳細介紹
1.自動獲取今天星期幾:
var aaa = '日一二三四五六' aaa.charAt(new Date().getDay()) //"日"
2.獲取今天日期格式(----年--月--日):
myDate.getFullYear()+'年'+(myDate.getMonth()+1)+'月'+myDate.getDate()+'日' //"2015年11月8日"
3.詳解
var myDate = new Date(); myDate.getYear(); //獲取當前年份(2位) myDate.getFullYear(); //獲取完整的年份(4位,1970-????) myDate.getMonth(); //獲取當前月份(0-11,0代表1月) myDate.getMonth()+1 myDate.getDate(); //獲取當前日(1-31) myDate.getFullYear()+'年'+(myDate.getMonth()+1)+'月'+myDate.getDate()+'日'; //"2015年11月8日"
myDate.getDay(); //獲取當前星期X(0-6,0代表星期天) myDate.getTime(); //獲取當前時間(從1970.1.1開始的毫秒數) 時間戳 myDate.getHours(); //獲取當前小時數(0-23) myDate.getMinutes(); //獲取當前分鍾數(0-59) myDate.getSeconds(); //獲取當前秒數(0-59) myDate.getMilliseconds(); //獲取當前毫秒數(0-999) myDate.toLocaleDateString(); //獲取當前日期 "2015/10/9" var mytime=myDate.toLocaleTimeString(); //獲取當前時間 "下午4:15:47" myDate.toLocaleString( ); //獲取日期與時間 "2015/10/9 下午4:15:47"
JS獲取當前時間戳的方法:
第一種方法:
var timestamp =Date.parse(new Date());
結果:1280977330000
第二種方法:
var timestamp =(new Date()).valueOf();
結果:1280977330748
第三種方法:
var timestamp=new Date().getTime();
結果:1280977330748
第一種:獲取的時間戳是把毫秒改成000顯示,
第二種和第三種是獲取了當前毫秒的時間戳。
我和同事在用js實現一個顯示出分析數據所剩大概時間的過程中,時間總是變給0,結果很怪異,最后發現獲取時間的時候用的是Date.parse(newDate())獲取的時間戳把毫秒改成了000顯示,所以時間差計算的不准確。
可以用第二種或第三種方法計算時間差。
js中單獨調用new Date(),例如document.write(new Date());
顯示的結果是:Mar 31 10:10:43 UTC+0800 2012 這種格式的時間
但是用new Date() 參與計算會自動轉換為從1970.1.1開始的毫秒數
將字符串形式的日期轉換成日期對象
var strTime="2011-04-16"; //字符串日期格式 var date= new Date(Date.parse(strTime.replace(/-/g, "/"))); //轉換成Data(); var month=date.getMonth()+1; //獲取當前月份
