Dinendal
Dinendal

Reputation: 279

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.

Upvotes: 0

Views: 1186

Answers (2)

kejn
kejn

Reputation: 112

You should use atoll instead. Please note the limits in <climits>.

Upvotes: 1

krzaq
krzaq

Reputation: 16421

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.

Upvotes: 2

Related Questions