具体如下代码,不赘述
#ifndef WEBTIMEGET_H
#define WEBTIMEGET_H
#include <QString>
#include <QVector>
#include <QObject>
#include <QDateTime>
#include <QtNetwork/QUdpSocket>
class webTimeGetter : public QObject
{
Q_OBJECT
public:
webTimeGetter();
virtual ~webTimeGetter();
public slots:
void readingData();
void connectSucess();
void tryGet();
private:
QVector<QString> hostList;
QUdpSocket* udpsocket;
QDateTime time;
};
#endif
//! ccsdu2004
#include <iostream>
#include "webTimeGetter.h"
webTimeGetter::webTimeGetter()
{
hostList.push_back("time.windows.com");
hostList.push_back("time.nist.gov");
udpsocket = new QUdpSocket(this);
connect(udpsocket,SIGNAL(connected()),this,SLOT(connectSucess()));
connect(udpsocket,SIGNAL(readyRead()),this,SLOT(readingData()));
}
webTimeGetter::~webTimeGetter()
{
}
void webTimeGetter::readingData()
{
QByteArray newTime;
QDateTime epoch(QDate(1900, 1, 1));
QDateTime unixStart(QDate(1970, 1, 1));
do
{
newTime.resize(udpsocket->pendingDatagramSize());
udpsocket->read(newTime.data(), newTime.size());
}while(udpsocket->hasPendingDatagrams());
QByteArray TransmitTimeStamp ;
TransmitTimeStamp=newTime.right(8);
quint32 seconds=TransmitTimeStamp[0];
quint8 temp=0;
for(int j=1;j<=3;j++)
{
seconds=seconds<<8;
temp=TransmitTimeStamp[j];
seconds=seconds+temp;
}
time.setTime_t(seconds-epoch.secsTo(unixStart));
std::cout<<time.date().year()<<std::endl;
std::cout<<time.date().month()<<std::endl;
std::cout<<time.date().day()<<std::endl;
std::cout<<time.time().hour()<<std::endl;
std::cout<<time.time().minute()<<std::endl;
udpsocket->disconnectFromHost();
udpsocket->close();
}
void webTimeGetter::connectSucess()
{
qint8 LI=0;
qint8 VN=3;
qint8 MODE=3;
qint8 STRATUM=0;
qint8 POLL=4;
qint8 PREC=-6;
QDateTime epoch(QDate(1900,1,1));
qint32 second=quint32(epoch.secsTo(QDateTime::currentDateTime()));
qint32 temp=0;
QByteArray timeRequest(48, 0);
timeRequest[0]=(LI <<6) | (VN <<3) | (MODE);
timeRequest[1]=STRATUM;
timeRequest[2]=POLL;
timeRequest[3]=PREC & 0xff;
timeRequest[5]=1;
timeRequest[9]=1;
timeRequest[40]=(temp=(second&0xff000000)>>24);
temp=0;
timeRequest[41]=(temp=(second&0x00ff0000)>>16);
temp=0;
timeRequest[42]=(temp=(second&0x0000ff00)>>8);
temp=0;
timeRequest[43]=((second&0x000000ff));
udpsocket->flush();
udpsocket->write(timeRequest);
udpsocket->flush();
}
void webTimeGetter::tryGet()
{
udpsocket->connectToHost(hostList.at(0),123);
}