You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JS日期格式化函数PC端正常,iOS(iPhone)端无法运行

iOS上JavaScript日期格式化代码失效的解决方案

问题原因

  1. replaceAll兼容性不足:这个方法是ES2021才新增的API,旧版本iOS Safari(iOS 14.5之前)不支持,而且你调用后没把结果赋值回变量——字符串是不可变的,这行代码等于白执行。
  2. 日期解析跨平台不兼容:iOS的Date构造函数对"2022-05-06 EDT"这种格式的解析支持很差,大概率会返回Invalid Date,后续调用getDate()、getMonth()等方法自然就会出错。

修复后的完整代码

function dateFormat(dateStr, type) {
    const dayOfWeek = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
    const month = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
    
    // 用正则替换替代replaceAll,兼容所有浏览器
    const formattedDateStr = dateStr.replace(/-/g, "/");
    // 先解析基础日期,避免直接拼接不兼容的时区缩写
    let date = new Date(formattedDateStr);
    
    // 如果需要转为EDT(美国东部夏令时,比UTC晚4小时),手动调整时间偏移
    // 若输入日期本身已是EDT时间,可跳过此步
    date.setHours(date.getHours() - 4);

    function daySuffix(d) {
        if (d > 3 && d < 21) return d + 'th';
        switch (d % 10) {
            case 1:  return d + "st";
            case 2:  return d + "nd";
            case 3:  return d + "rd";
            default: return d + "th";
        }
    }

    // 先检查日期是否有效,避免后续逻辑报错
    if (isNaN(date.getTime())) {
        return "invalid date format";
    }

    const day = daySuffix(date.getDate());
    let string = "";
    switch(type){
        case 'ld': 
            string = `${dayOfWeek[date.getDay()]}, ${month[date.getMonth()]} ${day}`;
            break;
        case 'sd': 
            string = `${month[date.getMonth()]} ${day}`;
            break;
        default: 
            string = "wrong type, ld or sd only";
    }
    console.log(string, 'string');
    return string;
}

console.log(dateFormat("2022-05-06","ld"));

核心修复说明

  • 把replaceAll换成replace(/-/g, "/"),保证所有浏览器都能识别,同时必须将替换结果赋值给新变量。
  • 移除直接拼接EDT时区缩写的写法,iOS Safari不识别这种时区标识。如果需要处理EDT时区,手动调整时间偏移即可(EDT比UTC晚4小时)。
  • 增加日期有效性校验,防止因无效日期导致后续逻辑崩溃。

内容的提问来源于stack exchange,提问作者DCR

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 10:48:19