關於datetime-local與時間戳相互轉化
阿新 • • 發佈:2019-01-27
HTML5中的新物件Datetime Local可用於本地時間選擇,是H5中很棒的新功能!在不考慮老版IE、FF的情況下能大大減少我們的開發花銷。
如:<input type="datetime-local" id="timer" />
1.可用Date物件的getTime()方法獲取時間戳!
如: var oTimer = document.getElementById('timer');
var timeStamp = new Date(oTimer.value).getTime();
2.如何給datetime-local賦值呢?
小夥伴都很聰明,認為那還不簡單,自己在Date物件擴充一個Format函式不就行了:
以下為網上找的一個函式,還不錯:
試試!! new Date(1459382400000).Format("yyyy-MM-dd HH:mm:ss");Date.prototype.Format = function(fmt) { //author: meizz var o = { "M+" : this.getMonth()+1, //月份 "d+" : this.getDate(), //日 "h+" : this.getHours(), //小時 "m+" : this.getMinutes(), //分 "s+" : this.getSeconds(), //秒 "q+" : Math.floor((this.getMonth()+3)/3), //季度 "S" : this.getMilliseconds() //毫秒 }; if(/(y+)/.test(fmt)) fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); for(var k in o) if(new RegExp("("+ k +")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length))); return fmt; };
得到。不錯不錯,搞定!????
我們試試:oTimer.value = new Date(1459382400000).Format("yyyy-MM-dd hh:mm:ss");
結果
我++,一定是我開啟的方式不對!!!F5F5F5F5F5F5...
其實,童鞋,你格式錯了!!!
應該是"yyyy-MM-ddThh:mm:ss"!
老子改了半天,你就給我看這個!!!
小一點的專案,邏輯簡單一點還好,能很快確定問題所在。一旦專案邏輯複雜一些,我還要去看我前面的存取、賦值邏輯是否有錯,那酸爽!!!!
其中的T即Time
原話:Note that the "T" appears literally in the string, to indicate the beginning of the time element, as specified in ISO8601.