UTC Time Conversion Trick

Handling Time Zone Differences in JSON Encoding/Decoding

When you encode and decode time values with JSON, you might encounter time zone discrepancies. The encoded time is converted to UTC, and when decoded, it reflects the time zone in which it is decoded. To mitigate this issue and retain the original time value, you can use the following function to adjust the time by your local time zone offset before encoding:


public time adjustTimeToUTC(time localTime, int offsetHours) {
    int yearG = year(localTime);
    int monthG = month(localTime);
    int dayG = day(localTime);
    int hourG = hour(localTime);
    int minuteG = minute(localTime);
    int secondG = second(localTime);

    hourG += offsetHours;
    while (hourG >= 24) {
        hourG -= 24;
        dayG++;
        if (dayG > makeTime(yearG, monthG, 1).daysInMonth()) {
            dayG = 1;
            monthG++;
            if (monthG > 12) {
                monthG = 1;
                yearG++;
            }
        }
    }
    while (hourG < 0) {
        hourG += 24;
        dayG--;
        if (dayG <= 0) {
            monthG--;
            if (monthG <= 0) {
                monthG = 12;
                yearG--;
            }
            dayG = makeTime(yearG, monthG, 1).daysInMonth();
        }
    }

    time adjustedTime = makeTime(yearG, monthG, dayG, hourG, minuteG, secondG);
    return adjustedTime;
}
    

To use this function, simply pass in your local time and the offset from UTC. For instance, if your local time is 6 hours behind UTC, you can adjust the time as follows:

time utcStartTime = adjustTimeToUTC(utcTimeStart, -6);

This adjustment ensures that when you encode the time into JSON and later decode it, you can apply the inverse of your time zone offset to retrieve the original time, thus avoiding any discrepancies due to time zone conversions.