yyyy-MM-dd HH:mm:ss
格式表示日期,如2018-11-11 00:00:00
,在js開發中也常常會把此格式字符串格式化爲javascript Date類型,如new Date('2018-11-11 00:00:00')
,不幸的是此操做在Safari瀏覽器(不管是Mac仍是iPhone)上會報錯,返回Invalid Date
。以下圖所示new Date('yyyy-MM-dd HH:mm:ss')
格式化前須要先把字符串轉化爲Safari支持的格式,能夠是yyyy/MM/dd HH:mm:ss
或yyyy-MM-ddTHH:mm:ss
或其餘。看下圖
new Date('2018-11-11 00:00:00'.replace(/-/g, "/")) new Date('2018-11-11 00:00:00'.replace(/ /g,"T"))
new Date('2018-11-11 00:00:00'.replace(/-/g, "/"))
/** * 在Safari和IE8上執行 new Date('2017-12-8 11:36:45'); 會獲得Invalid Date * 本函數重寫默認的Date函數,以解決其在Safari,IE8上的bug */ Date = function (Date) { MyDate.prototype = Date.prototype; return MyDate; function MyDate() { // 當只有一個參數而且參數類型是字符串時,把字符串中的-替換爲/ if (arguments.length === 1) { let arg = arguments[0]; if (Object.prototype.toString.call(arg) === '[object String]' && arg.indexOf('T') === -1) { arguments[0] = arg.replace(/-/g, "/"); // console.log(arguments[0]); } } let bind = Function.bind; let unbind = bind.bind(bind); return new (unbind(Date, null).apply(null, arguments)); } }(Date);
以下圖執行修改Date的方法後,正常使用new Date('2018-11-11 00:00:00')
將再也不報Invalid Date
javascript
注:這段代碼應該放在全部new Date操做以前,如html的<head>
中,以下圖是我在ionic項目中的配置位置
html
-
分割的日期,因此這裏建議用/
分割日期字符串,你也能夠不考慮IE8