QList<int> tradeDateCalendar::computeFrequencyTradeYearly(int date_, int minimumDate_, int maximumDate_) { QList<int> tradeDates; QDate yearDayCounter = QDate::fromJulianDay(minimumDate_); int dayOfYear = QDate::fromJulianDay(date_).dayOfYear(); forever { QDate yearDayComputation = yearDayCounter; int leapDayofYear = dayOfYear + (dayOfYear > 59 /* Feb 28th */ && QDate::isLeapYear(yearDayComputation.year()) ? 1 : 0); if (yearDayComputation.dayOfYear() > leapDayofYear) { yearDayComputation = yearDayComputation.addYears(1); leapDayofYear = dayOfYear + (dayOfYear > 59 /* Feb 28th */ && QDate::isLeapYear(yearDayComputation.year()) ? 1 : 0); } date_ = checkTradeDate(yearDayComputation.toJulianDay(), direction_ascending); if (date_ > maximumDate_) break; tradeDates.append(date_); yearDayCounter = yearDayCounter.addYears(1); } return tradeDates; }
// reimplemented from GraphicsButtonReceiver void CalendarGraphicsItem::buttonMouseReleaseEvent(QGraphicsItem * origin, QGraphicsSceneMouseEvent * /*event*/) { QDate date = _selectedDay; if(origin == _items["fastforward"]) date = date.addYears(1); else if(origin == _items["forward"]) date = date.addMonths(1); else if(origin == _items["rewind"]) date = date.addMonths(-1); else if(origin == _items["fastrewind"]) date = date.addYears(-1); setSelectedDay(date); }
void update() { QFile dataFile(fileName); if((!dataFile.open(QFile::ReadOnly))){ qDebug() << "Could not open file " + fileName; } else{ QFile dataFileTemp("temp.dat"); if((!dataFileTemp.open(QFile::WriteOnly))){ qDebug() << "Could not open file " + fileName; } QTextStream in(&dataFile); QTextStream out(&dataFileTemp); QDate currentDate = QDate::currentDate(); while(!in.atEnd()){ QString line = in.readLine(); //read one line at a time QStringList lineItems = line.split('|'); for (QStringList::iterator it = lineItems.begin();it != lineItems.end(); ++it){ QString current = *it; QDate date = QDate::fromString(current,Qt::ISODate); if(date.isValid()){ if(currentDate.year() > date.year()){ date.setDate(currentDate.year(),date.month(),date.day()); lineItems[0] = date.toString(Qt::ISODate); } if(date < currentDate){ if(QDate::isLeapYear(date.year())){ date = date.addYears(4); } else{ date = date.addYears(1); } lineItems[0] = date.toString(Qt::ISODate); line = lineItems.join("|"); out << line << endl; } else{ line = lineItems.join("|"); out << line << endl; } } } } dataFile.remove(); if(!dataFileTemp.rename("temp.dat",fileName)){ qDebug() << "Unable to change file name"; } } }
Schedule Schedule::fromOutlookCsvParsed(const QList<QStringList>& parsedCsv, const QTimeZone& timeZone, QString dateFormat, QString timeFormat) { const int START_DATE_POS = 0; const int START_TIME_POS = 1; const int START_SUBJECT_POS = 3; const int START_LOCATION_POS = 4; if (dateFormat.isEmpty()) dateFormat = "MM/dd/yyyy"; if (timeFormat.isEmpty()) timeFormat = "hh:mm AP"; Schedule schedule; for (int i = 0; i < parsedCsv.size(); ++i) { const QStringList& row = parsedCsv.at(i); QDate date = QDate::fromString(row.at(START_DATE_POS), dateFormat); QTime time = QTime::fromString(row.at(START_TIME_POS), timeFormat); if (date.year() < 2000) date = date.addYears(100); schedule.addEvent(date, time, row.at(START_SUBJECT_POS), row.at(START_LOCATION_POS), timeZone); } return schedule; }
QDate KMyMoneyGlobalSettings::firstFiscalDate() { QDate date = QDate(QDate::currentDate().year(), firstFiscalMonth(), firstFiscalDay()); if (date > QDate::currentDate()) date.addYears(-1); return date; }
QList<QString> ImportExport::months(quint8 aType, const QDate& aYear) { QList<QString> dataList; QSqlQuery selectMeasurement(mDataBase); quint64 startTimeStamp = QDateTime(aYear).toMSecsSinceEpoch(); quint64 endTimeStamp = QDateTime(aYear.addYears(1)).toMSecsSinceEpoch(); selectMeasurement.prepare( "SELECT " "timestamp " "FROM " "Measurement " "WHERE " "type = :type " "AND " "timestamp >= :startTimeStamp " "AND " "timestamp <= :endTimeStamp " "ORDER BY " "timestamp " "ASC;" ); selectMeasurement.bindValue(":type", aType); selectMeasurement.bindValue(":startTimeStamp", startTimeStamp); selectMeasurement.bindValue(":endTimeStamp", endTimeStamp); if (!selectMeasurement.exec()) { qDebug() << "FATAL selectMeasurement.exec(): " << selectMeasurement.lastError().databaseText() << " - " << selectMeasurement.lastError().driverText(); qDebug() << "Executed Query: " << selectMeasurement.executedQuery(); return dataList; } quint64 timestamp; QString monthStr; while (selectMeasurement.next()) { timestamp = selectMeasurement.value(0).toLongLong(); QDateTime monthDate = QDateTime::fromMSecsSinceEpoch(timestamp); monthStr = monthDate.toString("MMMM"); if (!dataList.contains(monthStr)) { dataList.push_back(monthStr); } } selectMeasurement.finish(); return dataList; }
QtDcm::QtDcm ( QWidget *parent ) : QWidget ( parent ), d ( new QtDcmPrivate ) { QTextCodec::setCodecForLocale( QTextCodec::codecForName ( "iso" ) ); setupUi ( this ); d->mode = QtDcm::CD_MODE; //Initialize QTreeWidgetPatients treeWidgetPatients->setColumnWidth ( 0, 400 ); treeWidgetPatients->setColumnWidth ( 1, 100 ); treeWidgetPatients->setColumnWidth ( 2, 100 ); const QStringList labelsPatients = QStringList() << "Patients name" << "ID" << "Birthdate" << "Sex"; treeWidgetPatients->setHeaderLabels ( labelsPatients ); treeWidgetPatients->setContextMenuPolicy ( Qt::CustomContextMenu ); //Initialize QTreeWidgetSeries treeWidgetStudies->setColumnWidth ( 0, 200 ); treeWidgetStudies->setColumnWidth ( 1, 100 ); const QStringList labelsStudies = QStringList() << "Studies description" << "Date" << "ID"; treeWidgetStudies->setHeaderLabels ( labelsStudies ); treeWidgetStudies->setContextMenuPolicy ( Qt::CustomContextMenu ); //Initialize QTreeWidgetSeries treeWidgetSeries->setColumnWidth ( 0, 230 ); treeWidgetSeries->setColumnWidth ( 1, 100 ); treeWidgetSeries->setColumnWidth ( 2, 100 ); const QStringList labelsSeries = QStringList() << "Series description" << "Modality" << "Date" << "ID"; treeWidgetSeries->setHeaderLabels ( labelsSeries ); treeWidgetSeries->setContextMenuPolicy ( Qt::CustomContextMenu ); //Initialize widgets QDate currentDate = QDate::currentDate(); startDateEdit->setDate ( currentDate.addYears(-100) ); endDateEdit->setDate ( currentDate ); QtDcmManager::instance()->setPatientsTreeWidget ( treeWidgetPatients ); QtDcmManager::instance()->setStudiesTreeWidget ( treeWidgetStudies ); QtDcmManager::instance()->setSeriesTreeWidget ( treeWidgetSeries ); QtDcmManager::instance()->setStartDate ( startDateEdit->date() ); QtDcmManager::instance()->setEndDate ( endDateEdit->date() ); initConnections(); }
ConfigureSessionsWidget::ConfigureSessionsWidget(QWidget *parent) : QWidget(parent), ui(new Ui::ConfigureSessionsWidget) { ui->setupUi(this); QDate defaultDate = QDate::currentDate().addMonths(-1); defaultDate = defaultDate.addYears(-1); ui->dateLimit->setDate(defaultDate); }
QDate FileName::highestVersionDate() const { QString fileQDatePattern = fileNameQDatePattern(); QPair<int, int> truncateRange(-1, -1); if (fileQDatePattern.contains("?")) { QString trueLengthName = name().replace(QRegExp("[{}]"), ""); truncateRange.first = trueLengthName.indexOf("?"); truncateRange.second = trueLengthName.lastIndexOf("?"); fileQDatePattern = fileQDatePattern.replace("?", ""); } QString file = name(); QDate result; QDate sputnikLaunch(1957, 10, 4); QString before = file.mid(0, file.indexOf("{")); QString after = file.mid(file.lastIndexOf("}") + 1); QStringList nameFilters; nameFilters.append(before + "*" + after); QStringList files = dir().entryList(nameFilters); // We can't sort the files to get our answer, so we need to go through every possible file. foreach (QString foundFile, files) { // Toss any numerical versioning sequence if (truncateRange.first >= 0 && truncateRange.second > truncateRange.first) { foundFile = foundFile.mid(0, truncateRange.first) + foundFile.mid(truncateRange.second + 1); } QDate fileDate = QDate::fromString(foundFile, fileQDatePattern); if (fileDate.isValid()) { // No missions before Sputnik 1, so we must be in the new millenium if (fileDate < sputnikLaunch) fileDate = fileDate.addYears(100); if (!result.isValid() || fileDate > result) { result = fileDate; } } } if (!result.isValid()) { throw IException(IException::Unknown, QObject::tr("No existing files found with a date version matching [%1] in " "[%2]") .arg(FileName(expanded()).name()).arg(path()), _FILEINFO_); } return result; }
static QDate date_by_amount_and_unit( int inAmount, int inUnit ) { const QDate current = QDate::currentDate(); switch ( inUnit ) { case Days: return current.addDays( inAmount ); break; case Weeks: return current.addDays( 7*inAmount ); break; case Months: return current.addMonths( inAmount ); break; case Years: return current.addYears( inAmount ); break; default: assert( !"Should not reach here" ); } return QDate(); }
void PmhEpisodeViewer::setPmhData(Internal::PmhData *pmh) { Q_ASSERT(pmh); if (!pmh) return; if (patient()) { // Create date delegates Utils::DateTimeDelegate *start = new Utils::DateTimeDelegate(this, true); Utils::DateTimeDelegate *end = new Utils::DateTimeDelegate(this, true); ui->tableView->tableView()->setItemDelegateForColumn(PmhEpisodeModel::DateStart, start); ui->tableView->tableView()->setItemDelegateForColumn(PmhEpisodeModel::DateEnd, end); QDate birth = patient()->data(Core::IPatient::DateOfBirth).toDate(); if (birth.isValid()) { start->setDateRange(birth, birth.addYears(150)); end->setDateRange(birth, birth.addYears(150)); } } d->m_Pmh = pmh; // If SimpleView -> test pmhepisodedata -> create a default one if (pmh->episodeModel()->rowCount()==0) { pmh->episodeModel()->insertRow(0); } ui->tableView->setModel(pmh->episodeModel()); ui->tableView->hideColumn(PmhEpisodeModel::IcdXml); ui->tableView->hideColumn(PmhEpisodeModel::Contact); ui->tableView->hideColumn(PmhEpisodeModel::EmptyColumn); #if QT_VERSION < 0x050000 ui->tableView->horizontalHeader()->setResizeMode(PmhEpisodeModel::Label, QHeaderView::Stretch); ui->tableView->horizontalHeader()->setResizeMode(PmhEpisodeModel::DateEnd, QHeaderView::Stretch); ui->tableView->horizontalHeader()->setResizeMode(PmhEpisodeModel::DateStart, QHeaderView::Stretch); #else // Qt5 ui->tableView->horizontalHeader()->setSectionResizeMode(PmhEpisodeModel::Label, QHeaderView::Stretch); ui->tableView->horizontalHeader()->setSectionResizeMode(PmhEpisodeModel::DateEnd, QHeaderView::Stretch); ui->tableView->horizontalHeader()->setSectionResizeMode(PmhEpisodeModel::DateStart, QHeaderView::Stretch); #endif }
bool CoreData::createDBFile(QString dbname) { if (QFile::exists(dbname)) { QFile::remove(dbname); } db.setDatabaseName(dbname); if (!db.open()) { QMessageBox::critical(0, QString::fromUtf8("出错了!"), QString::fromUtf8("无法打开数据库文件")); return false; } QSqlQuery query; query.exec("drop table people "); query.exec("create table people (id int primary key, name varchar(64), gender char(8), join_date date, status tinyint, comment text)"); qDebug() << db.lastError().type() << " + " << db.lastError().text(); query.exec("drop table date"); query.exec("create table date (id int primary key, date date)"); query.exec("pragma synchronous=0"); qDebug() << db.lastError().type() << " + " << db.lastError().text(); QDate date = QDate::currentDate(); date = date.addYears(-1); query.prepare("insert into date (id, date) values (?,?)"); int i = 0; QVariantList ids; QStringList dateStrings; for (i=0; i<3000; ++i) { ids<<i; date = date.addDays(1); dateStrings<<date.toString("yyyy-MM-dd"); } query.addBindValue(ids); query.addBindValue(dateStrings); if (!query.execBatch()) qDebug() << query.lastError(); query.exec("pragma synchronous=2"); qDebug()<<query.lastError(); query.exec("create table person_date (id int primary key, person_id integer, date_id integer, foreign key(person_id) references people(id), foreign key(date_id) references date(id))"); qDebug() << query.lastError(); personModel = new QSqlTableModel(0, db); setPersonModel(); signInModel = new SignInModel(0); setSignInModel(QDate::currentDate(), db); query.exec("create table contact (id int primary key, person_id integer, method varchar(64), value varchar(128), foreign key(person_id) references people(id))"); qDebug() << query.lastError(); return true; }
void Overview::on_rangeCombo_activated(int index) { p_profile->general->setLastOverviewRange(index); ui->dateStart->setMinimumDate(p_profile->FirstDay()); ui->dateEnd->setMaximumDate(p_profile->LastDay()); QDate end = p_profile->LastDay(); QDate start; if (index == 8) { // Custom ui->dateStartLabel->setEnabled(true); ui->dateEndLabel->setEnabled(true); ui->dateEnd->setEnabled(true); ui->dateStart->setEnabled(true); ui->dateStart->setMaximumDate(ui->dateEnd->date()); ui->dateEnd->setMinimumDate(ui->dateStart->date()); return; } ui->dateEnd->setEnabled(false); ui->dateStart->setEnabled(false); ui->dateStartLabel->setEnabled(false); ui->dateEndLabel->setEnabled(false); if (index == 0) { start = end.addDays(-6); } else if (index == 1) { start = end.addDays(-13); } else if (index == 2) { start = end.addMonths(-1).addDays(1); } else if (index == 3) { start = end.addMonths(-2).addDays(1); } else if (index == 4) { start = end.addMonths(-3).addDays(1); } else if (index == 5) { start = end.addMonths(-6).addDays(1); } else if (index == 6) { start = end.addYears(-1).addDays(1); } else if (index == 7) { // Everything start = p_profile->FirstDay(); } if (start < p_profile->FirstDay()) { start = p_profile->FirstDay(); } setRange(start, end); }
static void qwhereaboutsupdate_readRmcSentence(const QByteArray &sentence, QWhereaboutsUpdate *update, QWhereaboutsUpdate::PositionFixStatus *fixStatus) { QList<QByteArray> parts = sentence.split(','); if (parts.count() > 9) { QTime time; qwhereaboutsupdate_getTimeString(parts[1], &time); update->setUpdateTime(time); if (time.isValid()) { QDate date = QDate::fromString(parts[9], "ddMMyy"); date = date.addYears(100); // otherwise starts from 1900 update->setUpdateDateTime(QDateTime(date, time, Qt::UTC)); } } if (parts.count() > 6) { QWhereaboutsCoordinate coord; qwhereaboutsupdate_getUpdateCoordinate(&coord, parts[3], parts[4], parts[5], parts[6]); if (coord.type() != QWhereaboutsCoordinate::InvalidCoordinate) update->setCoordinate(coord); } if (parts.count() > 7) { bool hasSpeed = false; float speed = parts[7].toFloat(&hasSpeed); if (hasSpeed) update->setGroundSpeed(speed * 1.852 / 3.6); } if (parts.count() > 8) { bool hasCourse = false; float course = parts[8].toFloat(&hasCourse); if (hasCourse) update->setCourse(course); } if (fixStatus && parts.count() > 2) *fixStatus = qwhereaboutsupdate_fixStatusFromValidityFlag(parts[2]); }
void ReaderInfoDialog::okButtonClicked() { QString ID = IDLineEdit->text(); QString sql = "select * from reader where ID='" + ID + "'"; QSqlDatabase db = QSqlDatabase::database(); QSqlQuery query = db.exec(sql); if (query.isActive() && query.next()) { QMessageBox::information(this, tr("Error"), tr("The ID has use.")); return; } sql = "select * from admin where user_name='" + ID + "'"; db = QSqlDatabase::database(); query = db.exec(sql); if (query.isActive() && query.next()) { QMessageBox::information(this, tr("Error"), tr("The ID has use.")); return; } QString password1 = passwordLineEdit->text(); QString password2 = againPasswordLineEdit->text(); if (password1 != password2) { QMessageBox::information(this, tr("Error"), tr("Password error.")); return; } QString name = nameLineEdit->text(); QString sex = sexComboBox->currentText(); QString birthday = birthdayDateEdit->date().toString(Qt::ISODate); QDate date = cardDateEdit->date(); QString cardDate = date.toString(Qt::ISODate); QString validDate = validDateEdit->date().toString(Qt::ISODate); QString IDCard = IDCardLineEdit->text(); QString phone = phoneLineEdit->text(); int index = stateComboBox->currentIndex(); QString state = QString::fromLocal8Bit("ÆÕͨ"); if (index) { state = QString::fromLocal8Bit("×¢Ïú"); } index = typeComboBox->currentIndex(); QString type = QString::fromLocal8Bit("ÆÕͨ"); if (index) { type = "VIP"; } sql = "insert into reader values('" + ID + "','" + name + "','" + sex + "','" + birthday + "','" + cardDate + "','" + validDate + "','" + IDCard + "','" + phone + "','" + state + "','" + type + "')"; query = db.exec(sql); if (!query.isActive()) { QMessageBox::information(this, tr("Error"), query.lastError().text()); return; } sql = "insert into admin values('" + ID + "','" + password1 + "','0','0')"; query = db.exec(sql); sql = "insert into reader_log_info(ID,reader_ID,operation,operation_date) values('" + user_name + "','" + ID + "','add','" + QDateTime::currentDateTime().toString(Qt::ISODate) + "')"; query = db.exec(sql); if (query.isActive()) { QMessageBox::information(this, tr("Succeed"), tr("Add data succeed.")); IDLineEdit->clear(); passwordLineEdit->clear(); againPasswordLineEdit->clear(); nameLineEdit->clear(); sexComboBox->setCurrentIndex(0); QDate date = QDate::currentDate(); cardDateEdit->setDate(date); validDateEdit->setDate(date.addYears(1)); IDCardLineEdit->clear(); phoneLineEdit->clear(); } else { QMessageBox::information(this, tr("Error"), query.lastError().text()); } }
void DateSettingsEdit::setDateSettings() { if (active) return; // first lets disable everything active = true; fromDateEdit->setEnabled(false); toDateEdit->setEnabled(false); startDateEdit->setEnabled(false); thisperiod->setEnabled(false); prevperiod->setEnabled(false); lastn->setEnabled(false); lastnx->setEnabled(false); // the date selection types have changed if (radioSelected->isChecked()) { // current selection emit useStandardRange(); } else if (radioCustom->isChecked()) { // between x and y fromDateEdit->setEnabled(true); toDateEdit->setEnabled(true); // set date range using custom values emit useCustomRange(DateRange(fromDateEdit->date(), toDateEdit->date())); } else if (radioToday->isChecked()) { // current selected thru to today emit useThruToday(); } else if (radioLast->isChecked()) { // last n 'weeks etc' lastn->setEnabled(true); lastnx->setEnabled(true); QDate from; QDate today = QDate::currentDate(); // calculate range up to today... switch(lastnx->currentIndex()) { case 0 : // days from = today.addDays(lastn->value() * -1); break; case 1 : // weeks from = today.addDays(lastn->value() * -7); break; case 2 : // months from = today.addMonths(lastn->value() * -1); break; case 3 : // years from = today.addYears(lastn->value() * -1); break; } emit useCustomRange(DateRange(from, today)); } else if (radioFrom->isChecked()) { // from date - today startDateEdit->setEnabled(true); emit useCustomRange(DateRange(startDateEdit->date(), QDate::currentDate())); } else if (radioThis->isChecked()) { thisperiod->setEnabled(true); prevperiod->setEnabled(true); QDate today = QDate::currentDate(); QDate from, to; switch(thisperiod->currentIndex()) { case 0 : // weeks { int dow = today.dayOfWeek(); // 1-7, where 1=monday from = today.addDays(-1 * (dow-1)); to = from.addDays(6); // prevperiods from = from.addDays(prevperiod->value() * -7); to = to.addDays(prevperiod->value() * -7); } break; case 1 : // months from = QDate(today.year(), today.month(), 1); to = from.addMonths(1).addDays(-1); from = from.addMonths(prevperiod->value() * -1); to = to.addMonths(prevperiod->value() * -1); break; case 2 : // years from = QDate(today.year(), 1, 1); to = from.addYears(1).addDays(-1); from = from.addYears(prevperiod->value() * -1); to = to.addYears(prevperiod->value() * -1); break; } emit useCustomRange(DateRange(from, to)); } active = false; }
void XDateEdit::parseDate() { QString dateString = text().trimmed(); bool isNumeric; if (DEBUG) qDebug("%s::parseDate() with dateString %s, _currentDate %s, _allowNull %d", qPrintable(parent() ? parent()->objectName() : objectName()), qPrintable(dateString), qPrintable(_currentDate.toString()), _allowNull); #ifdef GUIClient_h QDate today = ofmgThis->dbDate(); #else QDate today = QDate::currentDate(); #endif if (_parsed) { if (DEBUG) qDebug("%s::parseDate() looks like we've already parsed this string", qPrintable(parent() ? parent()->objectName() : objectName())); return; } _valid = false; if (dateString == _nullString || dateString.isEmpty()) setNull(); else if (dateString == "0") // today setDate(today, TRUE); else if (dateString.contains(QRegExp("^[+-][0-9]+"))) // offset from today { int offset = dateString.toInt(&isNumeric); if (isNumeric) setDate(today.addDays(offset), true); } else if (dateString[0] == '#') // julian day { int offset = dateString.right(dateString.length() - 1).toInt(&isNumeric); if (isNumeric) setDate(QDate(today.year(), 1, 1).addDays(offset - 1), TRUE); } else if (dateString.contains(QRegExp("^[0-9][0-9]?$"))) // date in month { int offset = dateString.toInt(&isNumeric, 10); if (isNumeric) { if (offset > today.daysInMonth()) offset = today.daysInMonth(); setDate(QDate(today.year(), today.month(), 1).addDays(offset - 1), TRUE); } } else // interpret with locale { QString dateFormatStr = QLocale().dateFormat(QLocale::ShortFormat); if (DEBUG) qDebug("%s::parseDate() trying to parse with %s", qPrintable(parent() ? parent()->objectName() : objectName()), qPrintable(dateFormatStr)); QDate tmp = QDate::fromString(dateString, dateFormatStr); bool twodigitformat = !(dateFormatStr.indexOf(QRegExp("y{4}")) >= 0); if (tmp.isValid()) { if (twodigitformat && tmp.year() < 1950) // Qt docs say 2-digit years are 1900-based so { qDebug("%s::parseDate() found valid 2-digit year %d", qPrintable(parent() ? parent()->objectName() : objectName()), tmp.year()); tmp = tmp.addYears(100); // add backwards-compat with pre-3.0 DLineEdit qDebug("%s::parseDate() altered year to %d", qPrintable(parent() ? parent()->objectName() : objectName()), tmp.year()); } } else if (twodigitformat) { // try 4 digits, ignoring the possibility of '-literals in the format str dateFormatStr.replace(QRegExp("y{2}"), "yyyy"); if (DEBUG) qDebug("%s::parseDate() rewriting 2-digit year format string to %s", qPrintable(parent() ? parent()->objectName() : objectName()), qPrintable(dateFormatStr)); tmp = QDate::fromString(dateString, dateFormatStr); if (tmp.isValid()) { if (tmp.year() < 10) tmp = tmp.addYears(today.year() - today.year() % 100); if (DEBUG) qDebug("%s::parseDate() after changing to 4-digit year, year = %d", qPrintable(parent() ? parent()->objectName() : objectName()), tmp.year()); } else if (DEBUG) qDebug("%s::parseDate() after changing to 4-digit year, date still isn't valid", qPrintable(parent() ? parent()->objectName() : objectName())); } else { // try 2 digits, ignoring the possibility of '-literals in the format str dateFormatStr.replace(QRegExp("y{4}"), "yy"); if (DEBUG) qDebug("%s::parseDate() rewriting 4-digit year format string to %s", qPrintable(parent() ? parent()->objectName() : objectName()), qPrintable(dateFormatStr)); tmp = QDate::fromString(dateString, dateFormatStr); if (tmp.isValid() && tmp.year() < 1950) // Qt docs say 2-digit years are 1900-based so { qDebug("%s::parseDate() found valid 2-digit year %d", qPrintable(parent() ? parent()->objectName() : objectName()), tmp.year()); tmp = tmp.addYears(100); // add backwards-compat with pre-3.0 DLineEdit qDebug("%s::parseDate() altered year to %d", qPrintable(parent() ? parent()->objectName() : objectName()), tmp.year()); } } if(!tmp.isValid()) { // still no match -- we will decompose the format and input and // build a date based on that information QRegExp rx("(\\d+)"); QRegExp rx2("(m+|y+|d+)"); rx2.setCaseSensitivity(Qt::CaseInsensitive); QStringList numberList; QStringList formatList; int pos = 0; while ((pos = rx.indexIn(dateString, pos)) != -1) { numberList << rx.cap(1); pos += rx.matchedLength(); } pos = 0; while((pos = rx2.indexIn(dateFormatStr, pos)) != -1) { formatList << rx2.cap(1); pos += rx2.matchedLength(); } if (DEBUG) qDebug("%s::parseDate() aligning numberList %s with formatList %s", qPrintable(parent() ? parent()->objectName() : objectName()), qPrintable(numberList.join(":")), qPrintable(formatList.join(":"))); // if we don't have exactly 3 and the numberList is not 2 or 3 then don't bother if(formatList.size() == 3 && (numberList.size() == 2 || numberList.size() == 3)) { int year = today.year(); int day = -1; int month = -1; pos = 0; for (int i = 0; i < formatList.size(); ++i) { QChar ch = formatList.at(i).toLower().at(0); if(ch == 'y' && numberList.size() == 3) { year = numberList.at(pos).toInt(); pos++; } else if(ch == 'm') { month = numberList.at(pos).toInt(); pos++; } else if(ch == 'd') { day = numberList.at(pos).toInt(); pos++; } } // if single digit year, move it to the current century if (year < 10) year += today.year() - today.year() % 100; if(day > 0 && month > 0 && year > 0) tmp = QDate(year, month, day); } else if(formatList.size() == 3 && numberList.size() == 1) { QString ns = numberList.at(0); bool isNumber = false; (void)ns.toInt(&isNumber); if(isNumber && (ns.length() == 6 || ns.length() == 8)) { int year = today.year(); int day = -1; int month = -1; pos = 0; for (int i = 0; i < formatList.size(); ++i) { QChar ch = formatList.at(i).toLower().at(0); if(ch == 'y') { if(ns.length() == 8) { year = ns.mid(pos, 4).toInt(); pos+=4; } else { year = ns.mid(pos, 2).toInt(&isNumber); pos+=2; if(isNumber) { if(year < 50) year += 2000; else year += 1900; } } } else if(ch == 'm') { month = ns.mid(pos, 2).toInt(); pos+=2; } else if(ch == 'd') { day = ns.mid(pos, 2).toInt(); pos+=2; } } if(day > 0 && month > 0 && year > 0) tmp = QDate(year, month, day); } } } setDate(QDate(tmp.year(), tmp.month(), tmp.day()), true ); } if (!_valid) setText(""); _parsed = true; }
QDate FLUtil::addYears(const QDate &d, int ny) { return d.addYears(ny); }
Value ValueParser::tryParseDate(const QString& str, bool *ok) const { bool valid = false; QDate tmpDate = m_settings->locale()->readDate(str, &valid); if (!valid) { // Try without the year // The tricky part is that we need to remove any separator around the year // For instance %Y-%m-%d becomes %m-%d and %d/%m/%Y becomes %d/%m // If the year is in the middle, say %m-%Y/%d, we'll remove the sep. // before it (%m/%d). QString fmt = m_settings->locale()->dateFormatShort(); int yearPos = fmt.indexOf("%Y", 0, Qt::CaseInsensitive); if (yearPos > -1) { if (yearPos == 0) { fmt.remove(0, 2); while (fmt[0] != '%') fmt.remove(0, 1); } else { fmt.remove(yearPos, 2); for (; yearPos > 0 && fmt[yearPos-1] != '%'; --yearPos) fmt.remove(yearPos, 1); } //kDebug(36001) <<"Cell::tryParseDate short format w/o date:" << fmt; tmpDate = m_settings->locale()->readDate(str, fmt, &valid); } } if (valid) { // Note: if shortdate format only specifies 2 digits year, then 3/4/1955 // will be treated as in year 3055, while 3/4/55 as year 2055 // (because 55 < 69, see KLocale) and thus there's no way to enter for // year 1995 // The following fixes the problem, 3/4/1955 will always be 1955 QString fmt = m_settings->locale()->dateFormatShort(); if ((fmt.contains("%y") == 1) && (tmpDate.year() > 2999)) tmpDate = tmpDate.addYears(-1900); // this is another HACK ! // with two digit years, 0-69 is treated as year 2000-2069 (see KLocale) // however, in Excel only 0-29 is year 2000-2029, 30 or later is 1930 // onwards // the following provides workaround for KLocale so we're compatible // with Excel // (e.g 3/4/45 is Mar 4, 1945 not Mar 4, 2045) if ((tmpDate.year() >= 2030) && (tmpDate.year() <= 2069)) { QString yearFourDigits = QString::number(tmpDate.year()); QString yearTwoDigits = QString::number(tmpDate.year() % 100); // if year is 2045, check to see if "2045" isn't there --> actual // input is "45" if ((str.count(yearTwoDigits) >= 1) && (str.count(yearFourDigits) == 0)) tmpDate = tmpDate.addYears(-100); } } if (!valid) { //try to use the standard Qt date parsing, using ISO 8601 format tmpDate = QDate::fromString(str, Qt::ISODate); if (tmpDate.isValid()) { valid = true; } } if (ok) *ok = valid; return Value(tmpDate, m_settings); }
void XDateEdit::parseDate() { QString dateString = text().stripWhiteSpace(); bool isNumeric; if (DEBUG) qDebug("%s::parseDate() with dateString %s, _currentDate %s, _allowNull %d", qPrintable(parent() ? parent()->objectName() : objectName()), qPrintable(dateString), qPrintable(_currentDate.toString()), _allowNull); #ifdef OpenMFGGUIClient_h QDate today = ofmgThis->dbDate(); #else QDate today = QDate::currentDate(); #endif if (_parsed) { if (DEBUG) qDebug("%s::parseDate() looks like we've already parsed this string", qPrintable(parent() ? parent()->objectName() : objectName())); return; } _valid = false; if (dateString == _nullString || dateString.isEmpty()) setNull(); else if (dateString == "0") // today setDate(today, TRUE); else if (dateString.contains(QRegExp("^[+-][0-9]+"))) // offset from today { int offset = dateString.toInt(&isNumeric); if (isNumeric) setDate(today.addDays(offset), true); } else if (dateString[0] == '#') // julian day { int offset = dateString.right(dateString.length() - 1).toInt(&isNumeric); if (isNumeric) setDate(QDate(today.year(), 1, 1).addDays(offset - 1), TRUE); } else if (dateString.contains(QRegExp("^[0-9][0-9]?$"))) // date in month { int offset = dateString.toInt(&isNumeric, 10); if (isNumeric) { if (offset > today.daysInMonth()) offset = today.daysInMonth(); setDate(QDate(today.year(), today.month(), 1).addDays(offset - 1), TRUE); } } else // interpret with locale { QString dateFormatStr = QLocale().dateFormat(QLocale::ShortFormat); if (DEBUG) qDebug("%s::parseDate() trying to parse with %s", qPrintable(parent() ? parent()->objectName() : objectName()), qPrintable(dateFormatStr)); QDate tmp = QDate::fromString(dateString, dateFormatStr); if (tmp.isValid() && dateFormatStr.indexOf(QRegExp("y{2}")) >= 0) { qDebug("%s::parseDate() found valid 2-digit year %d", qPrintable(parent() ? parent()->objectName() : objectName()), tmp.year()); if (tmp.year() < 1950) // Qt docs say 2-digit years are 1900-based so { tmp = tmp.addYears(100); // add backwards-compat with pre-3.0 DLineEdit qDebug("%s::parseDate() altered year to %d", qPrintable(parent() ? parent()->objectName() : objectName()), tmp.year()); } } else { // try 4 digits, ignoring the possibility of '-literals in the format str dateFormatStr.replace(QRegExp("y{2}"), "yyyy"); if (DEBUG) qDebug("%s::parseDate() rewriting format string to %s", qPrintable(parent() ? parent()->objectName() : objectName()), qPrintable(dateFormatStr)); tmp = QDate::fromString(dateString, dateFormatStr); } setDate(QDate(tmp.year(), tmp.month(), tmp.day()), true ); } if (!_valid) setText(""); _parsed = true; }
void SvgView::loadPlan(vlePlan *plan) { qWarning() << "SvgView::loadPlan"; if ( mTplHeader.isNull() ) { // ToDo : improve error handling qWarning() << "SvgView::loadPlan() Template error"; return; } // Compute the height of a group if (mTplHeader.hasAttribute("height")) mGroupHeight = mTplHeader.attribute("height").toDouble(); else mGroupHeight = 100; // Compute size of the whole plan int planHeight = mGroupHeight * (1 + plan->countGroups()); int planWidth = (mMaxWidth * mZoomLevel); // Create SVG document QDomDocument planSVG("xml"); // Create root element QDomElement e = planSVG.createElement("svg"); e.setAttribute("width", QString(planWidth)); e.setAttribute("height", QString(planHeight)); e.setAttribute("viewBox", QString("0 0 %1 %2").arg(planWidth).arg(planHeight)); e.setAttribute("version", "1.1"); QDate dateStart = plan->dateStart(); QDate dateEnd = plan->dateEnd(); int nbDays = dateStart.daysTo(dateEnd); // In the plan duration is more than 1500 days if (nbDays > mMaxWidth) { // Update "pixel-per-day" to avoid very large picture qreal widgetSize = mMaxWidth; mPixelPerDay = (widgetSize / nbDays); } if (plan != mPlan) { qWarning() << "Plan period is from" << dateStart.toString("dd/MM/yyyy") << "to" << dateEnd.toString("dd/MM/yyyy") << "(" << nbDays<< "days)" << "[" << mPixelPerDay << "pixel per day]"; } // First insert the time rule QDomElement timeGrp = mTplHeader.cloneNode().toElement(); updateField(timeGrp, "{{name}}", ""); updatePos (timeGrp, 0, 0); updateAttr (timeGrp, "header_background", "width", QString::number(planWidth)); float yLen = (mPixelPerDay * 365 * mZoomLevel); // Show Weeks if (yLen > 2000) { QDate r; if (dateStart.daysInMonth() == 1) r.setDate(dateStart.year(), dateStart.month(), dateStart.day()); else r.setDate(dateStart.year(), dateStart.month() + 1, 1); while (r < dateEnd) { QDomElement newTimeStep = mTplTime.cloneNode().toElement(); if (yLen < 5000) updateField(newTimeStep, "{{name}}", r.toString("dd/MM") ); else updateField(newTimeStep, "{{name}}", r.toString("dd/MM/yy") ); updateAttr (newTimeStep, "step_block", "width", QString::number(4)); int offset = dateStart.daysTo(r); int aPos = (offset * mPixelPerDay * mZoomLevel); updatePos(newTimeStep, aPos, 0); timeGrp.appendChild(newTimeStep); r = r.addDays(7); } } // Show month else if (yLen > 500) { QDate r; if (dateStart.daysInMonth() == 1) r.setDate(dateStart.year(), dateStart.month(), dateStart.day()); else r.setDate(dateStart.year(), dateStart.month() + 1, 1); while (r < dateEnd) { QDomElement newTimeStep = mTplTime.cloneNode().toElement(); if (yLen < 1000) updateField(newTimeStep, "{{name}}", r.toString("MMM") ); else updateField(newTimeStep, "{{name}}", r.toString("MMM yy") ); updateAttr (newTimeStep, "step_block", "width", QString::number(4)); int offset = dateStart.daysTo(r); int aPos = (offset * mPixelPerDay * mZoomLevel); updatePos(newTimeStep, aPos, 0); timeGrp.appendChild(newTimeStep); r = r.addMonths(1); } } // Show Year else { QDate r; if (dateStart.dayOfYear() == 1) r.setDate(dateStart.year(), dateStart.month(), dateStart.day()); else r.setDate(dateStart.year() + 1, 1, 1); while (r < dateEnd) { QDomElement newTimeStep = mTplTime.cloneNode().toElement(); updateField(newTimeStep, "{{name}}", QString::number(r.year()) ); updateAttr (newTimeStep, "step_block", "width", QString::number(4)); int offset = dateStart.daysTo(r); int aPos = (offset * mPixelPerDay * mZoomLevel); updatePos(newTimeStep, aPos, 0); timeGrp.appendChild(newTimeStep); r = r.addYears(1); } } e.appendChild(timeGrp); // Insert all the known groups for (int i=0; i < plan->countGroups(); i++) { vlePlanGroup *planGroup = plan->getGroup(i); vlePlanActivity *prevActivity = 0; int prevLen = 0; int prevOffset = 0; // Create a new Group QDomElement newGrp = mTplHeader.cloneNode().toElement(); updateField(newGrp, "{{name}}", planGroup->getName()); updatePos (newGrp, 0, ((i + 1) * mGroupHeight)); updateAttr (newGrp, "header_background", "width", QString::number(planWidth)); for (int j = 0; j < planGroup->count(); j++) { vlePlanActivity *planActivity = planGroup->getActivity(j); QDate actStart = planActivity->dateStart(); QDate actEnd = planActivity->dateEnd(); qreal actLength = (mPixelPerDay * actStart.daysTo(actEnd) * mZoomLevel); if (actLength < 1) actLength = 1; QDomElement newAct = mTplTask.cloneNode().toElement(); updateField(newAct, "{{name}}", planActivity->getName()); updateAttr (newAct, "activity_block", "width", QString::number(actLength)); QString cfgColor("#00edda"); QString activityClass = planActivity->getClass(); if ( ! activityClass.isEmpty() ) { QString cfg = getConfig("color", activityClass); if ( ! cfg.isEmpty() ) cfgColor = cfg; } QString fillStyle = QString(";fill:%1").arg(cfgColor); updateAttr (newAct, "activity_block", "style", fillStyle, false); int date = dateStart.daysTo(planActivity->dateStart()); int aPos = (date * mPixelPerDay * mZoomLevel); if (prevActivity) { if (prevLen > aPos) { if (prevOffset < 40) prevOffset += 15; updateAttr(newAct, "activity_name", "y", QString::number(prevOffset)); } else prevOffset = 15; } updatePos(newAct, aPos, 0); newGrp.appendChild(newAct); prevActivity = planActivity; prevLen = aPos + (planActivity->getName().size() * 8); } e.appendChild(newGrp); } planSVG.appendChild( e ); QByteArray data; QTextStream stream(&data); planSVG.save(stream, QDomNode::EncodingFromTextStream); #ifdef PLAN_OUT QFile File("planOut.svg"); File.open( QIODevice::WriteOnly ); QTextStream TextStream(&File); planSVG.save(TextStream, 0); File.close(); mFilename = "planOut.svg"; #else mFilename.clear(); #endif mPlan = plan; QXmlStreamReader xData(data); mSvgRenderer->load(&xData); refresh(); }
/** * Apply variable modifiers to a QHash containing variables. * @param varModifierDefs [in] Variable modifier definitions. * @param vars [in, out] Variables to modify. * @param qDateTime [out, opt] If specified, QDateTime for the timestamp. * @return 0 on success; non-zero if any modifiers failed. */ int VarReplace::ApplyModifiers(const QHash<QString, VarModifierDef> &varModifierDefs, QHash<QString, QString> &vars, QDateTime *qDateTime) { // Timestamp construction. int year = -1, month = -1, day = -1; int hour = -1, minute = -1, second = -1; int ampm = -1; // TODO: Verify that all variables to be modified // were present in vars. QList<QString> varIDs = vars.keys(); foreach (const QString &id, varIDs) { if (!varModifierDefs.contains(id)) continue; QString var = vars.value(id); const VarModifierDef &varModifierDef = varModifierDefs[id]; // Always convert the string to num and char, // in case it's needed for e.g. useAs==month. int num = strToInt(var); num += varModifierDef.addValue; char chr = 0; if (var.size() == 1) { chr = var.at(0).toLatin1(); chr += varModifierDef.addValue; } // Apply the modifier. switch (varModifierDef.varType) { default: case VarModifierDef::VARTYPE_STRING: // Parse as a string. // Nothing special needs to be done here... break; case VarModifierDef::VARTYPE_NUMBER: // Parse as a number. (Base 10) var = QString::number(num, 10); break; case VarModifierDef::VARTYPE_CHAR: // Parse as an ASCII character. if (var.size() != 1) return -2; var = QChar::fromLatin1(chr); break; } // Pad the variable with fillChar, if necessary. if (var.size() < varModifierDef.minWidth) { var.reserve(varModifierDef.minWidth); QChar fillChar = QChar::fromLatin1(varModifierDef.fillChar); if (varModifierDef.fieldAlign == VarModifierDef::FIELDALIGN_LEFT) { while (var.size() < varModifierDef.minWidth) var.append(fillChar); } else /*if (variableDef.fieldAlign == VarModifierDef::FIELDALIGN_RIGHT)*/ { while (var.size() < varModifierDef.minWidth) var.prepend(fillChar); } } // Check if this variable should be used in the QDateTime. switch (varModifierDef.useAs) { default: case VarModifierDef::USEAS_FILENAME: // Not a QDateTime component. break; case VarModifierDef::USEAS_TS_YEAR: if (num >= 0 && num <= 99) { // 2-digit year. year = num + 2000; } else if (num >= 2000 && num <= 9999) { // 4-digit year. year = num; } else { // Invalid year. return -3; } break; case VarModifierDef::USEAS_TS_MONTH: { if (num >= 1 && num <= 12) month = num; else return -4; break; } case VarModifierDef::USEAS_TS_DAY: if (num >= 1 && num <= 31) day = num; else return -5; break; case VarModifierDef::USEAS_TS_HOUR: if (num >= 0 && num <= 23) hour = num; else return -6; break; case VarModifierDef::USEAS_TS_MINUTE: if (num >= 0 && num <= 59) minute = num; else return -7; break; case VarModifierDef::USEAS_TS_SECOND: if (num >= 0 && num <= 59) second = num; else return -8; break; case VarModifierDef::USEAS_TS_AMPM: // TODO: Implement this once I encounter // a save file that actually uses it. break; } // Update the variable in the hash. vars.insert(id, var); } if (qDateTime) { // Set the QDateTime to the current time for now. const QDateTime currentDateTime(QDateTime::currentDateTime()); *qDateTime = currentDateTime; // Adjust the date. QDate date = qDateTime->date(); const bool isDateSet = (year != -1 || month != -1 || day != -1); if (year == -1) { year = date.year(); } if (month == -1) { month = date.month(); } if (day == -1) { day = date.day(); } date.setDate(year, month, day); qDateTime->setDate(date); // Adjust the time. QTime time = qDateTime->time(); const bool isTimeSet = (hour != -1 || minute != -1); if (isDateSet && !isTimeSet) { // Date was set by the file, but time wasn't. // Assume default of 12:00 AM. time.setHMS(0, 0, 0); } else { if (hour == -1) { hour = time.hour(); } if (minute == -1) { minute = time.minute(); } if (second == -1) { second = 0; // Don't bother using the current second. } if (ampm != -1) { hour %= 12; hour += ampm; } time.setHMS(hour, minute, second); } qDateTime->setTime(time); // If the QDateTime is more than one day // in the future, adjust its years value. // (One-day variance is allowed due to timezone differences.) const QDateTime tomorrow = QDateTime::fromMSecsSinceEpoch( currentDateTime.toMSecsSinceEpoch() + (86400*1000), Qt::UTC); if (*qDateTime > tomorrow) { QDate adjDate = qDateTime->date(); int curYear = currentDateTime.date().year(); // NOTE: Minimum year of 2000 for GCN, // but Dreamcast was released in 1998. if (curYear > 1995) { // Update the QDateTime. qDateTime->setDate(adjDate.addYears(-1)); } } } // Variables modified successfully. return 0; }
bool PSV_Public::getDateTimeLabels(QDateTime &maxDateTime, QDateTime &minDateTime, QList<QPair<QVariant, QString> > &labelList) { labelList.clear(); QString dateFormat; int maxNum = 31; int days = minDateTime.daysTo(maxDateTime); int min_year = minDateTime.date().year(); int min_month = minDateTime.date().month(); int min_hour = minDateTime.time().hour(); int max_year = maxDateTime.date().year(); int max_month = maxDateTime.date().month(); int max_hour = maxDateTime.time().hour(); int hours = 24 * days + max_hour - min_hour; bool isDays = false; if(days < 2) { if(minDateTime.date() == maxDateTime.date()) { dateFormat = QString::fromLocal8Bit("hh时"); QDate tempDate = minDateTime.date(); for(int i = 0; i < 24; ++i) { QDateTime tempDateTime = QDateTime(tempDate,QTime(i,0,0)); labelList.append(QPair<QVariant,QString>(tempDateTime,tempDateTime.toString(dateFormat))); } QDateTime tempDateTime = QDateTime(tempDate,QTime(23,59,59)); labelList.append(QPair<QVariant,QString>(tempDateTime,QString::fromLocal8Bit("24时"))); } else { dateFormat = QString::fromLocal8Bit("MM月dd日 hh时"); int interval = 1; if(hours <= 12) { interval = 1; } else { interval = 2; } int tempHour = 0; int beginHour = 0; do { beginHour = tempHour ; tempHour += interval; }while(tempHour <= min_hour ); min_hour = beginHour; QDateTime tempDateTime = QDateTime(minDateTime.date(),QTime(min_hour,0,0)); labelList.append(QPair<QVariant,QString>(tempDateTime,tempDateTime.toString(dateFormat))); do { tempDateTime = tempDateTime.addSecs(3600 * interval); labelList.append(QPair<QVariant,QString>(tempDateTime,tempDateTime.toString(dateFormat))); }while(maxDateTime.secsTo(tempDateTime) <= 0); } } else if(days <= maxNum) { if(min_year == max_year) { dateFormat = QString::fromLocal8Bit("MM月dd日"); } else { dateFormat = QString::fromLocal8Bit("yyyy年MM月dd日"); } int flag = 0; if(QTime(0,0,0).secsTo(minDateTime.time()) > 0) { flag = -1; } int min_days = PSV_BEGIN_DATETIME.daysTo(QDateTime(minDateTime.date().addDays(flag),QTime(0,0,0))); flag = 0; if(QTime(0,0,0).secsTo(maxDateTime.time()) > 0) { flag = 1; } int max_days = PSV_BEGIN_DATETIME.daysTo(QDateTime(maxDateTime.date().addDays(flag),QTime(0,0,0))); if(min_days >= max_days) { max_days = max_days + 1; min_days = min_days - 1; } for(int i = min_days; i <= max_days; ++i) { QDateTime tempDateTime = PSV_BEGIN_DATETIME.addDays(i); labelList.append(QPair<QVariant,QString>(tempDateTime,tempDateTime.toString(dateFormat))); } // m_min_x = 86400 * min_days; // m_max_x = 86400 * max_days; } else { int interval = 1; isDays = true; dateFormat = QString::fromLocal8Bit("yyyy年MM月"); int years = max_year - min_year; if(years <= 1) { interval = 1; } else if( years <= 2) { interval = 2; } else if(years <= 3) { interval = 3; } else if(years <= 5) { interval = 6; } else { dateFormat = QString::fromLocal8Bit("yyyy年"); interval = 12; } int tempMonth = 1; int beginMonth =1; do { beginMonth = tempMonth; tempMonth += interval; }while(tempMonth <= min_month); min_month = beginMonth; QDate minDate = QDate(min_year,min_month,1); QDate maxDate = QDate(max_year,max_month,1).addMonths(1).addDays(-1); QDate tempDate = minDate; QDateTime tempDateTime = QDateTime(tempDate,QTime(0,0,0)); labelList.append(QPair<QVariant,QString>(tempDateTime,tempDateTime.toString(dateFormat))); do { if(isDays) { tempDate = tempDate.addYears(1); } else { tempDate = tempDate.addMonths(interval); } tempDateTime = QDateTime(tempDate,QTime(0,0,0)); labelList.append(QPair<QVariant,QString>(tempDateTime,tempDateTime.toString(dateFormat))); }while(maxDate > tempDate); } if(labelList.count() >= 2) { minDateTime = labelList.at(0).first.toDateTime(); if(isDays) { QDateTime tempDateTime = labelList.at(labelList.count() - 1).first.toDateTime().addDays(-1); maxDateTime = qMax(tempDateTime,maxDateTime); } else { maxDateTime = labelList.at(labelList.count() - 1).first.toDateTime(); } } else { // emit somethingMessage(tr("TTTTTTTT:901")); } return true; }
void Yahoo::buildGui () { setCaption(tr("Yahoo Quotes")); config.getData(Config::DataPath, dataPath); dataPath.append("/Stocks/Yahoo"); QString s = "new"; QString s2 = tr("New Symbol"); toolbar->addButton(s, newchart, s2); QObject::connect(toolbar->getButton(s), SIGNAL(clicked()), this, SLOT(newStock())); QLabel *label = new QLabel(tr("Method"), baseWidget); grid->addWidget(label, 0, 0); method = new QComboBox(baseWidget); method->insertItem("History", 0); method->insertItem("Auto History", 1); method->insertItem("Quote", 2); method->insertItem("Fundamental", 3); QObject::connect(method, SIGNAL(activated(int)), this, SLOT(methodChanged(int))); grid->addWidget(method, 0, 1); label = new QLabel(tr("Start Date"), baseWidget); grid->addWidget(label, 1, 0); sdate = new Q3DateEdit(QDate::currentDate(), baseWidget); sdate->setAutoAdvance(TRUE); sdate->setOrder(Q3DateEdit::YMD); grid->addWidget(sdate, 1, 1); label = new QLabel(tr("End Date"), baseWidget); grid->addWidget(label, 2, 0); edate = new Q3DateEdit(QDate::currentDate(), baseWidget); edate->setAutoAdvance(TRUE); edate->setOrder(Q3DateEdit::YMD); grid->addWidget(edate, 2, 1); QDate dt = QDate::currentDate(); if (dt.dayOfWeek() == 6) dt = dt.addDays(-1); else { if (dt.dayOfWeek() == 7) dt = dt.addDays(-2); } edate->setDate(dt); // suggest start date 12 years ago sdate->setDate(dt.addYears(-12).addDays(-1)); adjustment = new QCheckBox(tr("Adjustment"), baseWidget); grid->addWidget(adjustment, 3, 0); allSymbols = new QCheckBox(tr("All Symbols"), baseWidget); connect(allSymbols, SIGNAL(toggled(bool)), this, SLOT(allSymbolsChecked(bool))); grid->addWidget(allSymbols, 4, 0); QStringList l; list = new FileButton(baseWidget, l, dataPath); grid->addWidget(list, 4, 1); }
QDate qt1lCorrectDate(QDate date) { if (date.year() > qt1lBeginYear) return date; return date.addYears(100); }