Converting a UTC time to local time



  • Hi

    From data received I get a UTC time for an event (it actually comes in as 4-bit coded BCD).
    Is there some easy way to convert this to the local time?

    Thanks


  • Moderators

    @McLion

    int y = ...;
    int mm = ...;
    int d = ...;
    int h = ...;
    int m = ...;
    int s = ...;
    QDate date(y, mm, d);
    QTime time(h, m, s);
    QDateTime localTime = QDateTime(date, time, Qt::UTC).toLocalTime();
    

    Now you just need to fill up the ints (e.g. by bit shifting and masking) of your received data.



  • Thanks - works a treat.
    Here's my finished solution:

    uchar h = BCDtoHex(inData->at(18));
    uchar m = BCDtoHex(inData->at(19));
    uchar s = BCDtoHex(inData->at(20));
    QDate date;
    if(h > 12)  date = QDate::fromJulianDay((inData->at(16) << 8) + inData->at(17) + 2400001);
    else        date = QDate::fromJulianDay((inData->at(16) << 8) + inData->at(17) + 2400000);
    QTime time(h, m, s, 0);
    QDateTime localTime = QDateTime(date, time, Qt::UTC).toLocalTime();
    

    The JulianDate thing needs some testing since my input data is in ModifiedJulianDate.
    If it does not work like above I have an extensive calculation formula on hand. However, the above would be quicker.



  • I have a follow up question:
    Is there an easy way to 'add' times - despite doing it manually and take care of the 'carry-over' at 60 and stuff?

    uchar dh = BCDtoHex(inData->at(21));
    uchar dm = BCDtoHex(inData->at(22));
    uchar ds = BCDtoHex(inData->at(23));
    QTime duration(dh, dm, ds, 0);
    
    // now add this to time from above to get the endtime, i.e. something like:
    QTime end = time + duration; 
    
    QDateTime localEndTime = QDateTime(date, end, Qt::UTC).toLocalTime();
    

    Thanks


  • Moderators

    @McLion
    why don't you simply take a look at the QDateTime docs?! I am sure you will find the method on your own...



  • @raven-worx
    Seems I was not looking at the right place or not well enough.

    QTime zero(0, 0, 0, 0);
    QDateTime EndTimeLocal = StartTimeLocal.addSecs(zero.secsTo(duration));
    

    Thanks anyway :-)


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.