new Date兼容iOS和Android

本文介绍如何在iOS和Android上处理后端返回的日期字符串('YYYY-MM-DDHH:mm:ss'),解决因格式差异导致的JavaScript Date构造函数在不同平台上的问题。提供了一个自定义日期转换函数,以及兼容性解决方案,确保在前端正确获取和处理日期时间戳。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

new Date兼容iOS和Android

后端接口返回日期格式:YYYY-MM-DD HH:mm:ss

前端直接拿过来

const date = new Date('2020-11-13 11:28:30') 
const year = date.getFullYear(); // => NaN

发现报错了 获取到的值是 NaN

原因:

  • Android端是兼容以下两种日期格式的(YYYY-MM-dd HH:mm:ssYYYY/MM/dd HH:mm:ss), 所以在Android上允许以上代码是没有问题的。
  • iOS上只兼容(yyyy/MM/dd HH:mm:ss)格式 故需要把YYYY-MM-dd HH:mm:ss转换为`YYYY/MM/dd HH:mm:ss

解决方案:

const inputValue = '2020-11-13 11:28:30';
const str = inputValue.replace(/-/g, '/'); // 2020/11/13 11:28:30
const date = new Date(str) 
// code ...

返回距 1970 年 1 月 1 日之间的毫秒数:(对比时间)

// 不兼容写法
new Date(date).getTime()
// 兼容写法
new Date(data.replace(/-/g,'/')).getTime()

另附:定制时间格式转化Date(兼容IOS)

/**
 * @param format 默认 YYYY-MM-DD HH:mm:ss
 * */
export const dateConvert = (time, format = "YYYY-MM-DD HH:mm:ss") => {
  const date = new Date(time);
  // 这里是为了解决 IOS/Safari 中new Date()的兼容问题 
  if (typeof time == "string") {
    const arr = time && time.split(/[\-\+ :T]/);
    if (arr && arr.length > 0) {
      date.setUTCFullYear(arr[0]);
      date.setUTCMonth(arr[1] - 1);
      date.setUTCDate(arr[2]);
      date.setUTCHours(arr[3]);
      date.setUTCMinutes(arr[4]);
      date.setUTCSeconds(arr[5]);
    }
  }
  const o = {
    "M+": date.getMonth() + 1,                 //月份   
    "d+": date.getDate(),                    //日   
    "D+": date.getDate(),                    //日   
    "h+": date.getHours(),                   //小时   
    "H+": date.getHours(),                   //小时   
    "m+": date.getMinutes(),                 //分   
    "s+": date.getSeconds(),                 //秒   
    "q+": Math.floor((date.getMonth() + 3) / 3), //季度   
    "S": date.getMilliseconds()             //毫秒   
  };
  if (/(y+)|(Y+)/.test(format))
    format = format.replace(RegExp.$1 || RegExp.$2, (date.getFullYear() + "").substr(4 - (RegExp.$1.length || RegExp.$2.length)));
  for (const k in o)
    if (new RegExp("(" + k + ")").test(format))
      format = format.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  return format
}

// 可以把上述函数放入Date.prototype里面,调用更方便。
引用中提到,iOS系统对于JavaScript中的new Date()方法有格式要求。在小程序开发中,苹果手机无法正常处理带有"-"格式的日期字符串,只能处理带有"/"格式的日期字符串。所以在使用new Date()方法时,需要将日期字符串中的"-"替换为"/"才能在iOS上正常转换成日期对象。 引用中提供了解决办法,可以使用字符串的replace()方法将日期字符串中的"-"替换为"/"来解决兼容性问题。具体代码如下: ``` let dateStr = '2022-12-12'; let date = new Date(dateStr.replace(/-/g, '/')); // 将"-"替换为"/",得到兼容iOS的日期对象 ``` 这样,无论是在Android还是iOS上,都可以正常使用new Date()方法来转换日期字符串了。 引用中也提到了同样的问题,即在小程序中使用new Date()方法时,iOS手机需要将日期字符串中的"-"替换为"/"才能正常工作。解决办法也是使用字符串的replace()方法来进行替换。 综上所述,当在微信小程序中使用new Date()方法时,需要注意iOS系统对日期格式的要求,如果日期字符串中包含"-",则需要将其替换为"/"才能得到正确的日期对象。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [微信小程序new Date()方法失效问题解决方法](https://download.youkuaiyun.com/download/weixin_38637918/14014583)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [微信小程序 IOSnew Date()时间格式不兼容问题](https://blog.youkuaiyun.com/hhkongbai/article/details/127982842)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [微信小程序使用new Date(time)转格式的问题](https://blog.youkuaiyun.com/qq_38004125/article/details/123575298)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值