Conversion from JSON to time

Converting JSON Time Strings to Time Data Type

When receiving time information in JSON format, such as "2023-11-24T06:00:00.000Z", it is often in UTC format. Directly using this string in a time-sensitive application may lead to incorrect time representations due to local time zone differences. To correctly convert this UTC time string to the local `time` data type, we can use a custom function in WinCC OA. This function parses the string and creates a `time` object that accurately reflects the local time it represents.

The Issue:

JSON-encoded time is in UTC format, which can lead to discrepancies when used directly in time zones other than UTC.

The Solution:

The custom function below takes the JSON time string and converts it into a `time` data type:


public time TimeConversion(string timeString){
    string startTimeProxy = timeString;
    dyn_string startDateTimeSplit = startTimeProxy.split("T");
    string startDateSplitZ = startDateTimeSplit.at(0);
    string startDateSplitO = startDateTimeSplit.at(1);

    dyn_string startDateSplitZS = startDateSplitZ.split("-");
    dyn_string startDateSplitOS = startDateSplitO.split(":");

    string startDateSplitOSO = startDateSplitOS.at(1);
    dyn_string startDateSplitOSOS = startDateSplitOSO.split(".");

    int startYear = (int)startDateSplitZS.at(0);
    int startMonth = (int)startDateSplitZS.at(1);
    int startDay = (int)startDateSplitZS.at(2);

    int startHour = (int)startDateSplitOS.at(0);
    int startMinute = (int)startDateSplitOSOS.at(0);

    time startTime = makeTime(startYear, startMonth, startDay, startHour, startMinute, 0);
    return startTime;
}
    

How to Use:

Simply pass the JSON time string to the function. The function will parse the string and return a `time` data type that corresponds to the time represented in the string, adjusted to the local time zone:

time localTime = TimeConversion("2023-11-24T06:00:00.000Z");

Nuances:

The function assumes that the input time string is in a specific format, typically ISO 8601. If the time string format varies, the function may need to be adjusted accordingly. Additionally, it currently does not handle time zones or daylight saving time changes automatically. For such cases, further enhancements to the function might be necessary.