Muduo library timestamp, Date, timezone analysis

Source: Internet
Author: User
Tags time zones julian day

    • Timestamp class
    • Date class
    • TimeZone class

First, learn about a structure of time and a function to get time.

#include <time.h>struct timeval  {      __time_t tv_sec;        /* Seconds. */      __suseconds_t tv_usec;  /* Microseconds. */  

Tv_sec refers to the number of seconds from Epoc to present.
Tv_usec refers to the number of microseconds from the epoch to the present.
Epoch refers to a specific time: 1970-01-01 00:00:00 UTC.

function to get time

#include <sys/time.h>int gettimeofday(struct timeval* tv,struct timezone× tz )

Put the current time information on the TV and place the local time zone information in TZ (if you don't need to be nullable). This function is a function provided by the C library that calls the Sys_gettimeofday system call in the encapsulation implementation, so the system call is called in the final analysis.

For more information about the time, refer to Here

Timestamp class

The class structure code is as follows:

Class Timestamp: PublicMuduo::copyable, Publicboost::less_than_comparable<timestamp>{ Public:Timestamp();ExplicitTimestamp (int64_t microsecondssinceepocharg);voidSwap (timestamp& that);stringToString ()Const;stringtoFormattedString (BOOLShowmicroseconds =true)Const;BOOLValid ()Const{returnMicrosecondssinceepoch_ >0; } int64_t Microsecondssinceepoch ()Const; time_t Secondssinceepoch ()Const;StaticTimestamp now ();StaticTimestamp Invalid ();StaticTimestamp fromunixtime (time_t t)StaticTimestamp Fromunixtime (time_t t,intmicroseconds);Static Const intKmicrosecondspersecond = +* +;Private: int64_t Microsecondssinceepoch_;};

Inheriting public muduo::copyable means you can replicate, that is, value passing. The inherited public boost::less_than_comparable represents a size comparison (!=,>,<=,>=), and when implemented, only < and = = can be implemented, others can be generated automatically; The overloads of the comparison operators are implemented in the form of friends.

The variable Microsecondssinceepoch_ maintains the epoch-to-present microsecond number, defining the const static variable Kmicrosecondspersecond in order to facilitate the conversion between microseconds and seconds. Microsecondssinceepoch_ is a int64_t type that has different type representations on 32-bit and 64-bit computers, as defined below:

# if __WORDSIZE == 64longint              int64_t;# elselonglongint      int64_t;#endif

Some of the functions defined in this function are for the purpose of obtaining a certain format time, and the string is related to converting the time to string format. Can be used to test, get the current time, convert to string.

#include <muduo/base/Timestamp.h>#include<stdio.h>usingnamespace muduo;int main(){    Timestamp timeStamp=Timestamp::now();    printf("it‘s %lld microseconds from Epoch\n", timeStamp.microSecondsSinceEpoch());    string str= timeStamp.toString();    printf("sting format is %s\n", str.c_str());    return0;}
Date class

The class code is as follows:

Class Date: Publicmuduo::copyable{ Public:structYearmonthday {intYear//[1900..2500]    intMonth//[1..12]    intDay//[1..31]};Static Const intKdaysperweek =7;Static Const intkjuliandayof1970_01_01;  Date (); Date (intYearintMonthintDay);ExplicitDate (intJuliandaynum);ExplicitDate (Const structtm&);voidSwap (date& that);BOOLValid ()Const{returnJuliandaynumber_ >0; }stringToisostring ()Const;structYearmonthday Yearmonthday ()Const;intYear ()Const;intMonth ()Const;intDay ()Const;//[0, 1, ..., 6] = [Sunday, Monday, ..., Saturday]  intWeekDay ()Const;intJuliandaynumber ()Const{returnJuliandaynumber_; }Private:intJuliandaynumber_;};

The date is expressed in Julian Day, and what is Julian days, probably the number of years before the January 1, 4713 BC, can be found here in Wikipedia or Baidu encyclopedia.

The private variable Juliandaynumber_ stores this number of days, defines the structure Yearmonthday facilitates the conversion between the two, Toiosstring converts the date to string.

You can test it:

#include <muduo/base/Date.h>#include <iostream>using namespaceMuduo;intMain () {Date date ( -,7, -);intJuliandaynum=date.juliandaynumber ();STD::cout<<"Julian Day Num is"<<julianDayNum<<STD:: Endl; Date Date2 (Juliandaynum);structDate::yearmonthday Yearmonthday=date2.yearmonthday ();STD::cout<<yearMonthDay.year<<"--"<<yearMonthDay.month<<"--"<<yearMonthDay.day<<STD:: Endl;return 0;}
TimeZone class

Let's look at a data structure

#include <time.h>structTM {intTm_sec;/ * seconds – The value interval is [0,59] * /    intTm_min;/* min-value interval is [0,59] */    intTm_hour;/* When-the value interval is [0,23] */    intTm_mday;/* Date in one months-the value interval is [1,31] */    intTm_mon;/* Month (starting from January, 0 for January) The value interval is [0,11] */    intTm_year;/ * Year with a value equal to the actual year minus 1900 * /    intTm_wday;/ * Week – The value interval is [0,6], where 0 stands for Sunday, 1 for Monday, and so on * /          intTm_yday;/ * Number of days starting January 1 of each year – the value interval is [0,365], where 0 is January 1, 1 is January 2, and so on .          intTM_ISDST;/ * Daylight Saving time identifier, the TM_ISDST is positive when daylight savings is applied. Without daylight saving time, TM_ISDST is 0 and TM_ISDST () is negative when the situation is not known. */};

There is also a type time_t. time_t represents the time (calendar time) from a point in time (for example: January 1, 1970 0:0 0 seconds) to this time the number of seconds, it is a long integer,
Calendar time is represented by the time_t data type, and the time represented by time_t (calendar time) is the number of seconds from a point in time (for example: January 1, 1970 0:0 0 seconds) to this time. In Time.h, we can also see that time_t is a long integer, representing a time not later than January 18, 2038 19:14 07 seconds

The TimeZone class is designed to facilitate conversion between time zones, as well as between seasonal transitions. It is defined as follows:

//TimeZone for 1970~2030Class TimeZone: Publicmuduo::copyable{ Public:Explicit TimeZone(Const Char* Zonefile); TimeZone (intEASTOFUTC,Const Char* Tzname);//A fixed timezoneTimeZone () {}//An invalid timezone  BOOLValid ()Const;structTM ToLocalTime (time_t Secondssinceepoch)Const; time_t Fromlocaltime (Const structtm&)Const;Static structTM Toutctime (time_t Secondssinceepoch,BOOLYday =false);Statictime_t Fromutctime (Const structtm&);Statictime_t Fromutctime (intYearintMonthintDayintHourintMinuteintseconds);structData;//forward Declaration Private: Boost::shared_ptr<data> Data_;};

TimeZone (int eastofutc, const char* Tzname) constructor, Eastofutc represents UTC time. The time difference between the Chinese mainland and UTC is +8, which is utc+8. The United States is UTC-5.

You can write a test code:

#include <muduo/base/TimeZone.h>#include <muduo/base/Timestamp.h>#include <time.h>#include <iostream>using namespaceMuduo;voidPrinttm (structtm& T) {STD::cout<<T.tm_year<<"-"<<T.tm_mon<<"-"<<T.tm_mday<<STD:: Endl;STD::cout<<T.tm_hour<<"-"<<T.tm_min<<"-"<<T.tm_sec<<STD:: Endl;STD::cout<<T.tm_wday<<STD:: Endl;}intMain () {Timestamp timestamp=timestamp::now ();structTM T=timezone::toutctime (Timestamp.secondssinceepoch ());    Printtm (T); TimeZone TimeZone (8,"China");structTM T2=timezone.tolocaltime (Timestamp.secondssinceepoch ()); Printtm (T2);return 0;}

Operation Result:

115-6-2711-51-341115-6-2711-51-421

Year is calculated from 1900, so 115 stands for 2015.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Muduo library timestamp, Date, timezone analysis

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.