1

I'm trying to convert milliseconds to a formatted time string using the following:

function getTimeString(timeMs) {
    return Qt.formatTime(new Date(timeMs), "h:mm:ss");
}

The problem is, when I give it 1 hour worth of time, instead of displaying 1:00:00 it displays 20:00:00. Two hours similarly displays 21:00:00. This is because of the timezone offset built into the Date object. There are some functions to remove the timezone offset that sound promising, but fall short, such as:

  • Date.getUTCDate() which turns the QML Date object into a javascript Date object that can no longer be passed into Qt.formatTime(), and javascript seems to have no suitable alternative time formatting.
  • Date.toUTCString() which doesn't take a format, so I would need some string manipulation to cut the unwanted parts out.

I could always just use repeated divisions and manually build the string from that, but what I have is fairly short and clear, and I'd like to keep it that way if possible.

  • Here is an already provided solution. It works for me in my project https://stackoverflow.com/a/35890816/5903276 You can try this – Ramkumar R Jan 21 '21 at 18:03
  • @RamkumarR While not a bad solution, it has to same problem as Date.toUTCString(). I'll have to do string manipulations (though not many) to get what I want instead of being able to use a custom format. For instance, I'll have to check and conditionally remove the leading 0, which "h:mm:ss" takes care of automatically. –  Jan 21 '21 at 18:43

1 Answers1

0

I had the same problem and solved it by manually adding the timezone offset and converting to locale string, which allows to add a format:

var date = new Date(timestamp)
date.setMinutes(date.getMinutes() + date.getTimezoneOffset())

return date.toLocaleString(Qt.locale(), "dd. MMMM yyyy hh:mm:ss")

Not sure though, if this works with all timezones, I have only tested de_DE

SyntaX
  • 328
  • 2
  • 8