轉眼又到了周末,轉眼又要上班,轉眼...大概這就是一眼萬年的意思吧。
這周繼續IM(即時聊天),項目用的是LayIM移動端改裝的,僅僅“借用”了一個聊天窗口。由於是內嵌App的頁面,自然少不了Android和iOS的兼容問題,這次要談的就是日期格式在iOS的bug。
一般我們在頁面渲染時間的時候都是xxxx-xx-xx,ios系統new Date(xxxx-xx-xx)的時候會報NaN-NaN-NaN NaN:NaN異常,將xxxx-xx-xx的時間格式改為xxxx/xx/xx就可以解決這個問題。使用正則轉換:
/* 轉換為時間戳 */ function formatTimeStamp(date){ return Date.parse(new Date(date)) || Date.parse(new Date(date.replace(/-/g,'/'))); } formatTimeStamp('2017-11-11');
JavaScript默認的時間格式我們一般情況下不會用,所以需要進行格式化,下面說說JavaScript時間格式化方法。
很多時候,我們可以利用JavaScript中Date對象的內置方法來格式化,如:
var d = new Date(); console.log(d); // 輸出:Mon Nov 04 2013 21:50:33 GMT+0800 (中國標准時間) console.log(d.toDateString()); // 日期字符串,輸出:Mon Nov 04 2013 console.log(d.toGMTString()); // 格林威治時間,輸出:Mon, 04 Nov 2013 14:03:05 GMT console.log(d.toISOString()); // 國際標准組織(ISO)格式,輸出:2013-11-04T14:03:05.420Z console.log(d.toJSON()); // 輸出:2013-11-04T14:03:05.420Z console.log(d.toLocaleDateString()); // 轉換為本地日期格式,視環境而定,輸出:2013年11月4日 console.log(d.toLocaleString()); // 轉換為本地日期和時間格式,視環境而定,輸出:2013年11月4日 下午10:03:05 console.log(d.toLocaleTimeString()); // 轉換為本地時間格式,視環境而定,輸出:下午10:03:05 console.log(d.toString()); // 轉換為字符串,輸出:Mon Nov 04 2013 22:03:05 GMT+0800 (中國標准時間) console.log(d.toTimeString()); // 轉換為時間字符串,輸出:22:03:05 GMT+0800 (中國標准時間) console.log(d.toUTCString()); // 轉換為世界時間,輸出:Mon, 04 Nov 2013 14:03:05 GMT
如果上面的方法不能滿足我們的要求,也可以自定義函數來格式化時間,如:
// 對Date的擴展,將 Date 轉化為指定格式的String // 月(M)、日(d)、小時(h)、分(m)、秒(s)、季度(q) 可以用 1-2 個占位符, // 年(y)可以用 1-4 個占位符,毫秒(S)只能用 1 個占位符(是 1-3 位的數字) // 例子: // (new Date()).format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423 // (new Date()).format("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18 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; }
調用:
// var date = 時間戳或者其他new Date能轉換的格式 new Date(date).format(“yyyy-MM-dd”);
更多擴展時間處理方法見:https://www.cnblogs.com/chenwenhao/p/10480234.html