I'm trying to parse date time from a PNG file but can't quite get it with QRegExp
this_png_20211208_1916.png
QDateTime Product::GetObstime()
{
QDateTime obstime;
QString filename = FLAGS_file_name.c_str();
QString year, month, day, hour, minute, second;
QRegExp regexp = QRegExp("^.*\\w+_(\\d{4}\\d{2}\\d{2})_(\\d{2}\\d{2})\\.png$");
VLOG(3) << " filename: " << filename.toStdString();
if(regexp.indexIn(filename) !=-1)
{
VLOG(3) << " filename: " << filename.toStdString();
QStringList dt_bits = regexp.capturedTexts();
if(dt_bits.size() >=2)
{
year = dt_bits.at(1).mid(0, 4);
month = dt_bits.at(1).mid(5, 2);
day = dt_bits.at(1).mid(8, 2);
hour = dt_bits.at(2).mid(0, 2);
minute = dt_bits.at(2).mid(3, 2);
second = dt_bits.at(2).mid(3, 2);
VLOG(3) << " Year: " << year.toStdString()
<< " Month: " << month.toStdString()
<< " Day: " << day.toStdString()
<< " Hour: " << hour.toStdString()
<< " Min: " << minute.toStdString()
<< " Sec: " << second.toStdString();
QString datetime_str = year + "-" + month + "-" + day +
"T" + hour + ":" + minute + second + "00Z";
obstime = QDateTime::fromString(datetime_str, Qt::ISODate);
if (obstime.isValid())
{
VLOG(3)<<"Date iS VALID: "<<obstime.toString(Qt::ISODate).toStdString();
}
else
{
LOG(ERROR)<<" Error! Date Time bits did not match format.";
}
}
}
return obstime;
}
been using tools like https://regex101.com/
but to no avail. am I missing something?
You have the following errors in your code:
month = dt_bits.at(1).mid(5, 2);
should be month = dt_bits.at(1).mid(4, 2);
because the index is 0-based, not 1-basedday = dt_bits.at(1).mid(8, 2);
should be day = dt_bits.at(1).mid(6, 2);
minute = dt_bits.at(2).mid(3, 2);
should be minute = dt_bits.at(2).mid(2, 2);
second = dt_bits.at(2).mid(3, 2);
should be second = "00";
because your filenames do not contain secondsGenerally I would recommend doing all of the work in the regex instead of doing some fancy splitting using QString::mid()
:
QRegExp regexp = QRegExp("^.*\\w+_(\\d{4})(\\d{2})(\\d{2})_(\\d{2})(\\d{2})\\.png$");
This gives you all the fields in separate groupings, no need for QString::mid()
at all.