【问题标题】:iOS Safari displays different data from .toLocaleString() and .slice()iOS Safari 显示来自 .toLocaleString() 和 .slice() 的不同数据
【发布时间】:2016-02-21 04:33:34
【问题描述】:

我正在通过 .ajax 为我制作的一个简单的天气应用程序附加来自 Dark Sky API 的数据。

当您点击每天的预报时,您会看到附加信息,包括日出/设定时间,以及最低和最高温度的时间。在 Windows 机器上查看时,一切看起来都很好。但在 iPhone 上查看时,上述时间显示不正确。我用于附加数据的代码如下:

//THIS DATA IS RETURNED INACCURATELY ON IOS-------------------------
                    var sunsetTime = new Date(forecast.sunsetTime * 1000);
                    sunsetTime = sunsetTime.toLocaleString();
                    sunsetTime = sunsetTime.slice(11, 15) + 'PM';

                    var sunriseTime = new Date(forecast.sunriseTime * 1000);
                    sunriseTime = sunriseTime.toLocaleString();
                    sunriseTime = sunriseTime.slice(11, 15) + 'AM';

                    var minTempTime = new Date(forecast.temperatureMinTime * 1000);
                    minTempTime = minTempTime.toLocaleString();
                    minTempTime = minTempTime.slice(11, 15) + 'AM';


                    var maxTempTime = new Date(forecast.temperatureMaxTime * 1000);
                    maxTempTime = maxTempTime.toLocaleString();
                    maxTempTime = maxTempTime.slice(11, 16) + 'PM';
                    //END OF INACCURATE RETURNS-------------------------------------------

在 iOS 上,时间显示为“,20AM”或“,20PM”。我不确定如何在 iPhone 上进行调试,因此我们将不胜感激。

我的代码笔的链接:http://codepen.io/DDD37/pen/GozGGx

【问题讨论】:

    标签: javascript ios iphone mobile-safari


    【解决方案1】:

    经过更多研究,我发现.toLocaleString() 根据浏览器返回不同格式的数据。我已更改代码以将时间从 new Date 变为...

     var sunsetTime = new Date(forecast.sunsetTime * 1000);
                        sunsetTime = sunsetTime.toString();
                        sunsetTime = sunsetTime.slice(16, 21);
                        sunsetTime = tConvert(sunsetTime);
    

    ...具有将 24 小时制改为 12 小时制的功能...

      //Funciton to convert 24 hour time to 12:
    function tConvert(time) {
        // Check correct time format and split into components
        time = time.toString().match(/^([01]\d|2[0-3])(:)([0-5]\d)(:[0-5]\d)?$/) || [time];
    
        if (time.length > 1) { // If time format correct
            time = time.slice(1); // Remove full string match value
            time[5] = +time[0] < 12 ? 'am' : 'pm'; // Set AM/PM
            time[0] = +time[0] % 12 || 12; // Adjust hours
        }
        return time.join(''); // return adjusted time or original string
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-19
      • 1970-01-01
      • 2016-11-16
      • 1970-01-01
      • 2016-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多