实验
QTime和字符串相互转换
QDate和字符串相互转换
QDateTime和字符串相互转换
QCalendarWidget使用
year,month,day,minute,second,msec,dayOfWeek, dayto方法/属性的使用
布局
datetimeexample.cpp
#include "datetimeexample.h"
#include "ui_datetimeexample.h"
#include <QMessageBox>dateTimeExample::dateTimeExample(QWidget *parent): QWidget(parent), ui(new Ui::dateTimeExample)
{ui->setupUi(this);
}dateTimeExample::~dateTimeExample()
{delete ui;
}void dateTimeExample::on_btnReadNow_clicked()
{QDateTime curDateTime =QDateTime::currentDateTime();//读取到当前的日期时间ui->timeEdit->setTime(curDateTime.time()); //取time()ui->editTime->setText(curDateTime.toString("HH:mm:ss"));ui->dateEdit->setDate(curDateTime.date()); //取date()ui->editDate->setText(curDateTime.toString("yyyy-MM-dd"));ui->dateTimeEdit->setDateTime(curDateTime);ui->editDateTime->setText(curDateTime.toString("yyyy-MM-dd HH:mm:ss"));
}void dateTimeExample::on_btnSetTime_clicked()
{QString str = ui->editTime->text();str= str.trimmed();if(!str.isEmpty()){QTime tm = QTime::fromString(str,"HH:mm:ss");ui->timeEdit->setTime(tm);}
}void dateTimeExample::on_btnSetDate_clicked()
{QString str = ui->editDate->text();str= str.trimmed();if(!str.isEmpty()){QDate dt = QDate::fromString(str,"yyyy-MM-dd");ui->dateEdit->setDate(dt);}
}void dateTimeExample::on_btnSetDateTime_clicked()
{QString str = ui->editDateTime->text();str= str.trimmed();if(!str.isEmpty()){QDateTime datetime = QDateTime::fromString(str,"yyyy-MM-dd HH:mm:ss");ui->dateTimeEdit->setDateTime(datetime);}
}void dateTimeExample::on_btnShowDateTime_clicked()
{QDateTime curDateTime = QDateTime::currentDateTime();QDate dt2;dt2.setDate(2025,01,01);QString temp = curDateTime.toString("yyyy-MM-dd HH:mm:ss zzz");QString str=QString("当前日期时间:%1").arg(temp);str+="\n";str+=QString("年:%1").arg(curDateTime.date().year());str+="\n";str+=QString("月:%1").arg(curDateTime.date().month());str+="\n";str+=QString("月:%1").arg(curDateTime.date().day());str+="\n";str+=QString("时:%1").arg(curDateTime.time().hour());str+="\n";str+=QString("分:%1").arg(curDateTime.time().minute());str+="\n";str+=QString("秒:%1").arg(curDateTime.time().second());str+="\n";str+=QString("毫秒:%1").arg(curDateTime.time().msec());str+="\n";str+="-----------------------------\n";str+=QString("星期:%1").arg(curDateTime.date().dayOfWeek());str+="\n";str+=QString("toLocal8Bit().data():%1").arg(temp.toLocal8Bit().data());str+="\n";str+=QString("距离%1还有:%2天").arg(dt2.toString("yyyy年MM月dd日")).arg(curDateTime.date().daysTo(dt2));QMessageBox::information(this,"信息",str);}void dateTimeExample::on_calendarWidget_selectionChanged()
{QDate date = ui->calendarWidget->selectedDate();ui->editCalendar->setText(date.toString("yyyy年MM月dd日"));
}
效果