问题描述
最近在使用uniapp开发App时,需要将后端发过来的 格式为 “yyyy-MM-dd HH:mm:ss"的格式转化为 “yyyy-MM-dd”,在Android平台并无任何问题,但是在iOS上出现了NaN的问题,效果如下图所示
起初我以为是 uniapp的bug,但是查询相关资料发现是 iOS上的WebView的问题,iOS的Date不识别 “-”,所以解决思路就是 在 new Date(sz)之前,将字符串所有的“-”替换为”/",具体的代码
/**
* @description 简述:时间格式
* @param date: 时间 eg:new Date()
* @param fmt:格式 eg:yyyy-MM-dd HH:mm:ss yyyy-MM-dd
* @return String
* @example timeFormat(new Date(), "yyyy-MM-dd HH:mm:ss") or timeFormat("2022-02-13", "yyyy-MM-dd HH:mm:ss")
* */
export function timeFormat(date, fmt = "yyyy-MM-dd") {
if (date == null || date == '' || date == undefined)
return "";
if(typeof(date) == "string") {
// 判断系统平台属于哪个平台,如果是其它开发前端框架,则需要调整这行代码
if (uni.getSystemInfoSync().platform == 'ios') {
// 解决ios手机时间格式化NaN问题
date = date.replace(/-/g,'/')
}
date = new Date(date)
}
else if (!(date instanceof Date)) {
date = new Date(date)
}
var o = {
"M+": date.getMonth() + 1, //月份
"d+": date.getDate(), //日
"H+": date.getHours(), //小时
"m+": date.getMinutes(), //分
"s+": date.getSeconds(), //秒
"q+": Math.floor((date.getMonth() + 3) / 3), //季度
"S": date.getMilliseconds() //毫秒
};
if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.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;
}
如何调用
timeFormat(new Date(), "yyyy-MM-dd HH:mm:ss")
timeFormat("2022-02-13", "yyyy-MM-dd HH:mm:ss")