本文實(shí)例為大家分享了js時(shí)間戳與日期格式之間相互轉(zhuǎn)換的代碼,供大家參考,具體內(nèi)容如下
1. 將時(shí)間戳轉(zhuǎn)換成日期格式
// 簡(jiǎn)單的一句代碼 var date = new Date(時(shí)間戳); //獲取一個(gè)時(shí)間對(duì)象 /** 1. 下面是獲取時(shí)間日期的方法,需要什么樣的格式自己拼接起來(lái)就好了 2. 更多好用的方法可以在這查到 -> http://www.w3school.com.cn/jsref/jsref_obj_date.asp */ date.getFullYear(); // 獲取完整的年份(4位,1970) date.getMonth(); // 獲取月份(0-11,0代表1月,用的時(shí)候記得加上1) date.getDate(); // 獲取日(1-31) date.getTime(); // 獲取時(shí)間(從1970.1.1開始的毫秒數(shù)) date.getHours(); // 獲取小時(shí)數(shù)(0-23) date.getMinutes(); // 獲取分鐘數(shù)(0-59) date.getSeconds(); // 獲取秒數(shù)(0-59)
例子
// 比如需要這樣的格式 yyyy-MM-dd hh:mm:ss var date = new Date(1398250549490); Y = date.getFullYear() + '-'; M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-'; D = date.getDate() + ' '; h = date.getHours() + ':'; m = date.getMinutes() + ':'; s = date.getSeconds(); console.log(Y+M+D+h+m+s); //呀麻碟 //
2. 將日期格式轉(zhuǎn)換成時(shí)間戳
// 也很簡(jiǎn)單 var strtime = '2014-04-23 18:55:49:123'; var date = new Date(strtime); //傳入一個(gè)時(shí)間格式,如果不傳入就是獲取現(xiàn)在的時(shí)間了,這樣做不兼容火狐。 // 可以這樣做 var date = new Date(strtime.replace(/-/g, '/')); // 有三種方式獲取,在后面會(huì)講到三種方式的區(qū)別 time1 = date.getTime(); time2 = date.valueOf(); time3 = Date.parse(date); /* 三種獲取的區(qū)別: 第一、第二種:會(huì)精確到毫秒 第三種:只能精確到秒,毫秒將用0來(lái)代替 比如上面代碼
3. Date()參數(shù)形式有7種
new Date("month dd,yyyy hh:mm:ss"); new Date("month dd,yyyy"); new Date("yyyy/MM/dd hh:mm:ss"); new Date("yyyy/MM/dd"); new Date(yyyy,mth,dd,hh,mm,ss); new Date(yyyy,mth,dd); new Date(ms);
比如:
new Date("September 16,2016 14:15:05"); new Date("September 16,2016"); new Date("2016/09/16 14:15:05"); new Date("2016/09/16"); new Date(2016,8,16,14,15,5); // 月份從0~11 new Date(2016,8,16); new Date(1474006780);
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com