main.cpp
#include "settime.h"
#include <QtCore/QCoreApplication>
#include <QString>
#include <sys/time.h>
#include <unistd.h>
#include <QDebug>
int gettimeofday(struct timeval *tv, struct timezone *tz);
int settimeofday(const struct timeval *tv, const struct timezone *tz);
int SetSystemTime(int, int, int, int, int, int);
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QTextStream out (stdout);
if (argc < 3)
{
out<<"Usage : timeset XXXX-XX-XX XX:XX:XX"<<endl;
exit(0);
}
int nyear;
int nmonth;
int nday;
int nhour;
int nminute;
int nsecond;
const char *s_ctime = "settime";
const char *s_cinTime = argv[0];
QString timer =QString::fromLocal8Bit(*argv,128);
if (QString::compare(s_ctime,s_cinTime)==0)
{
bool ok;
QString year= timer.mid(8, 4);
QString month = timer.mid(13,2);
QString day = timer.mid(16,2);
QString hour = timer.mid(19,2);
QString second = timer.mid(22,2);
QString minute = timer.mid(25,2);
nyear = year.toInt(&ok,10);
nmonth = month.toInt(&ok,10);
nday = day.toInt(&ok,10);
nhour = hour.toInt(&ok,10);
nminute = minute.toInt(&ok,10);
nsecond = second.toInt(&ok,10);
}
SetSystemTime(nyear,nmonth,nday,nhour,nminute,nsecond);
time_t timep;
time (&timep);
qDebug()<<"Now the time is :"<<asctime(gmtime(&timep));
return a.exec();
}
settime.cpp
#include "settime.h"
#include <sys/time.h>
#include <unistd.h>
#include <QDebug>
int SetSystemTime(int year,int month,int day,int hour, int minute,int second)
{
struct rtc_time tm;
struct tm _tm;
struct timeval tv;
time_t timep;
_tm.tm_sec = second;
_tm.tm_min = minute;
_tm.tm_hour = hour;
_tm.tm_mday = day;
_tm.tm_mon = month - 1;
_tm.tm_year = year - 1900;
timep = mktime(&_tm);
tv.tv_sec = timep;
tv.tv_usec = 0;
if(settimeofday (&tv, (struct timezone *) 0) < 0)
{
printf("Set system datatime error!\n");
return -1;
}
return 0;
}
settime.h
#ifndef SETTIME_H
#define SETTIME_H
struct rtc_time
{
int tm_sec;
int tm_min;
int tm_hour;
int tm_mday;
int tm_mon;
int tm_year;
int tm_wday;
int tm_yday;
int tm_isdst;
};
#endif
运行结果: