Dinendal Dinendal - 25 days ago 23
C++ Question

Qt/C++ - Convert string timestamp to uint

I want to create a date but my timestamp is in a char*.

So I'm trying to convert to int but with atoi() or toInt() I don't get it.

qDebug() << atoi("1478790756754"); /* give 2147483647 */

QString tmp = "1478790756754";
qDebug() << tmp.toInt(); /* give 0 */


The aim is to get the date, with dateTime.setTime_t() for example.

Answer

Your timestamp seems to be in the milliseconds since 1.1.1970 format. This obviously doesn't fit a 32-bit integer, as is the int type on your architecture.

The solution is simple: convert to a type with larger value range, i.e. long long:

QString tmp = "1478790756754";
QDateTime date = QDateTime::fromMSecsSinceEpoch(tmp.toLongLong());

QString's conversion functions also have an out parameter pointer to bool. You can pass a bool variable and test it to check if the conversion was successful.

Comments