Search code examples
javascriptiosiphonemobile-safari

iOS Safari displays different data from .toLocaleString() and .slice()


I'm appending data from the Dark Sky API via .ajax for a simple weather app I made.

When you click on the forecast for each day, you are shown additional info with the sunrise/set time, and time of day for min and max temperatures. When viewed on a Windows machine, everything looks fine. But when viewed on an iPhone the above mentioned times are displayed improperly. The code I'm using for the data being appended is as follows:

//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-------------------------------------------

On iOS the times are display as ",20AM" or ",20PM" I'm not sure how to go about debugging on an iPhone so any help will be greatly appreciated.

A link to my code pen: http://codepen.io/DDD37/pen/GozGGx


Solution

  • After much more research I found that .toLocaleString() returns differently formatted data depending upon the browser. I'm changed my code to get the time from new Date to...

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

    ...with a function to change 24-hour time to 12-hour time...

      //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
    }