Converting ISO::DateTime to number format - qt

I want to change the date time format to numbers only so that it can be incremented.
Current Implementation is saved as QString 2019-03-13T09:01:22+01:0
Expected result: 201903120858031

qt is a really powerful framework, you are just coding a solution in a wrong way.
Imagine the pain in the back just validating dates, leap years etc etc
every date and dateTime has the methods to do calendar math operations.
see this example as ref:
//
QDateTime dateOrigin = QDateTime::currentDateTime();
QDateTime ReturnDate = QDateTime::currentDateTime();
QString isoDate{dateOrigin.toString(Qt::ISODate)};
qDebug() << "before: " << isoDate;
ReturnDate = dateOrigin.addDays(1);
ReturnDate = dateOrigin.addMonths(1);
ReturnDate = dateOrigin.addYears(1);
qDebug() << "after: " << ReturnDate.toString(Qt::ISODate);
//
update:
lets suppose that 201903120858031 is a date time formated as yyyyMMddHHmmss, then you can convert that to a long
//201903120858031
//yyyyMMddHHmmss
qDebug() << "after: " << ReturnDate.toString("yyyyMMddHHmmss");
qDebug() << "after as long number: " << ReturnDate.toString("yyyyMMddHHmmss").toLong();
producing the output:
before: "2019-02-28T12:43:33"
after: "20200228124333"
after as number: 20200228124333

Related

How to efficiently deserialize nvp dictionary from std::string using boost

Suppose I have a stringified representation of a name-value-pair dictionary with custom separators between names/values and name-value pairs, e.g. "foo:4|bar:-1" or "Alice=>cat;Bob=>dog".
It can be done with boost's split(), but I was curious if firstly, doing so isn't just reinventing the wheel, secondly, there are more efficient alternatives, like some customized deserialization.
Consider using Boost Spirit. Using the X3 version you'd write
const std::string input = "foo:4|bar:-1"; // or "Alice=>cat;Bob=>dog";
auto text = +~x3::char_(":|");
std::map<std::string, int> parsed;
if (parse(input.begin(), input.end(), (text >> ':' >> x3::int_) % '|', parsed)) {
std::cout << "parsed[bar]: " << parsed["bar"] << "\n";
}
Live On Coliru
The other form:
const std::string input = "Alice=>cat;Bob=>dog";
auto text = +(x3::char_ - ';' - "=>");
std::map<std::string, std::string> parsed;
if (parse(input.begin(), input.end(), (text >> "=>" >> text) % ';', parsed)) {
std::cout << "parsed[Bob]: " << parsed["Bob"] << "\n";
}
Live On Coliru

Display month and day in localized format

I need to get correct month and day format for various locales.
I have QLable and QDate, label must display month and day. I try format date by QLocale.
//Yes, I got system locale and set is as default
QLocale::toString(date, "MMMM d");
But result is incorrect.
For example, "MMMM d" in German locale equal to:
"d. MMMM"
for French is:
"d MMMM"
How to transform "MMMM d" format to locale settings in Qt 4.8?
Thanks!
P.S. In javascript I use following code
var date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
var options = {month: 'long', day: 'numeric' };
console.log(date.toLocaleDateString('de-DE', options));
One way to do it would be to parse QLocale::LongFormat:
#include <QtGui>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QList<QLocale> locales;
locales << QLocale(QLocale::English);
locales << QLocale(QLocale::German);
locales << QLocale(QLocale::French);
locales << QLocale(QLocale::Russian);
locales << QLocale(QLocale::Chinese);
locales << QLocale(QLocale::Korean);
foreach(QLocale locale, locales) {
QString format = locale.dateFormat(QLocale::LongFormat);
QRegExp rx("([^d]d(?!d)[^,;]?\\s?|M+.?){2}");
rx.indexIn(format);
QString localed = rx.cap(0).trimmed();
qDebug() << locale.bcp47Name() << "\t" << localed << "\t" << locale.toString(QDateTime::currentDateTime(), localed);
}
return app.exec();
}
Outputs:
"en-US" "MMMM d" "March 17"
"de-DE" "d. MMMM" "17. März"
"fr-FR" "d MMMM" "17 mars"
"ru-RU" "d MMMM" "17 марта"
"zh-CN" "M月d日" "3月17日"
"ko-KR" "M월 d일" "3월 17일"
So, I used ICU library. DateTimePatternGenerator solve my problem

Construct a QByteArray from a HEX value entered as a QString

If QString str = "0xFFFF", how to turn this text representation of an hex into a QByteArray? In the end, I would like to have the same of what I get from the following:
QByteArray ba;
ba.resize(2);
ba[0] = 0xFF;
ba[1] = 0xFF;
In either case the final QByteArray would be a sequence of hex values, i.e. FFFF. Conversion should be applied on that string. Given that, if your input string is provided prepended with the 0x, you should get rid of it via mid().
Here is a code snippet which compares the results of the two approaches: manually filling the QByteArray with hex values or converting hex values from a QString:
QByteArray array1;
array1.resize(2);
array1[0] = 0xFF;
array1[1] = 0xFF;
QString str = "0xFFFF";
QString value = str.mid(2); // "FFFF" <- just the hex values!
QByteArray array2 = QByteArray::fromHex(value.toLatin1());
qDebug() << array1; // not printable chars
qDebug() << array2;
qDebug() << array1.toHex(); // to have a printable form use "toHex()"!
qDebug() << array2.toHex();

how to set/read QSqlRelationalTableModel column properties and constraints?

Is there any way to check properties and constraints for each column in a QSqlRelationalTableModel? For example, I'd like to ask my QSqlRelationalTableModel object whether a certain column can contain nulls, or what datatype is valid for that column.
You'll need to get a QSqlField value for each column of the model, which is given by
QSqlRecord record = model->database().record(model->tableName());
QSqlField field = record.field(columnIndex);
then you'll be able to check if a field can be null with QSqlField::requiredStatus() (if the driver supports querying that property) and to get its data type with QSqlField::type().
From alexisdm's answer above, I wrote this simple code snippet to output the properties of each field in a table. Posting it here to save typing for anyone else who is interested.
I also discovered a gotcha: if you use table_model::record() or table_model::record(int) you get unexpected (to me) results for some properties, e.g., isAutoValue seems to always return false, even for fields designated as autoincrement fields in the database. However, you do get a real value for typeID() (though I haven't been able to determine what typeID() is), whereas typeID() always returned -1 for me using model->database().record(model->tableName()).
QSqlRecord record = table_model->database().record(table_model->tableName());
// the following get isAutoValue() wrong; but have a real typeID()
//QSqlRecord record = table_model->record();
//QSqlRecord record = table_model->record(table_model->rowCount() - 1);
qDebug() << "********** table" << table_model->tableName() << "*********";
for (int i = 0; i < table_model->columnCount(); ++i) {
QSqlField field = record.field(i);
qDebug() << "---------- field" << i << field.name() << "--------";
qDebug() << "default value" << field.defaultValue();
qDebug() << "is auto value" << field.isAutoValue();
qDebug() << "is generated" << field.isGenerated();
qDebug() << "is null" << field.isNull();
qDebug() << "is read only" << field.isReadOnly();
qDebug() << "is valid" << field.isValid();
qDebug() << "length" << field.length();
qDebug() << "precision" << field.precision();
qDebug() << "required status" << field.requiredStatus();
qDebug() << "type" << field.type();
qDebug() << "type id" << field.typeID();
qDebug() << "value" << field.value();
}

Qt QDateTime nanoseconds from 1/1/1970

I am about to read data From a File which has stored it's time in nanoseconds from 1/1/1970. My problem is I want to read it to a QDateTime object, but it simply does not work as I want it to and the Qt Documentation did not help me either.
Note: milliseconds raster is enough for my purposes
Here my current approach:
void setDateTime(qint64 &ns)
{
_datetime.setDate(QDate(1970,1,1));
_datetime.setTime(QTime(0,0,0,0));
ns /= 1000; //ns are now ms
qDebug() << "| ms = " << ns;
qDebug() << "| days = " << static_cast<int>(ns%(60*60*24*1E6));
_datetime.addDays( static_cast<int>(ns%(60*60*24*1000)) );
_datetime.addMSecs( ns - ((ns/(60*60*24*1000))*60*60*24*1E6) );
qDebug() << "| dt = " << _datetime;
}
the result is always
| dt = QDateTime("Thu Jan 1 00:00:00 1970")
which is surely wrong
Can anybody tell where my flaw is? Thanks for any tips and help.
Edit: setTime_t is obviously what I wanted (except for msec resolution), and that works as expected, but I am really curious why the above approach does not work.
Edit changed hack-away bug from 1E6 multiplicative to 1E6
QDateTime::addDays() and QDateTime::addMSecs() are const functions returning a new QDateTime. You're simply throwning the return value away.
And yes, this is written in the documentation.

Resources