c++ share with c's time conversion example

  • 2020-05-26 10:00:42
  • OfStack

1. Time in C++ :
(1) time_t is actually a 64-bit long int type
(2) time function:
Function introduction:
Function name: time
Header file: time.h
Function prototype: time_t time(time_t *timer)
Function: Get the current system time, the result is 1 time_t type, which is actually a large integer, whose value is the number of seconds from CUT (Coordinated Universal Time) time 00:00:00 on January 1, 1970 (called UNIX system Epoch time) to the current time, and then call localtime to convert CUT time represented by time_t to the local time (we are a +8 zone, 8 hours longer than CUT) and converted to the struct tm type, table the data members of this type respectively to show the time minutes and seconds of year, month, day.
Display system current time:


int main()
{ 
time_t ltime;
time(&ltime);
cout<<ctime(&time);
return 0;
}

ctime function:
char *ctime(const time_t *timer);
timer:time_t type pointer
Return value: string in the format of "week, month, day, hour: minute: second year \n\0"


localtime function :(gmtime function is similar)
struct tm *localtime(const time_t *timer);
timer: pointer to time_t type
Return value: time pointer in tm structure


asctime function:
char *asctime(const struct tm *timeptr);
timeptr: pointer to structure tm
Return value: string in the format of "week, month, day, hour: minute: second year \n\0"
Ex. :


#include<stdio.h>   
#include <stddef.h>   
#include <time.h>   
int main(void)   
{
time_t timer;  //time_t is long int  type 
struct tm *tblock;
timer = time(NULL);// this 1 The sentence can also be changed time(&timer);
tblock = localtime(&timer);
printf("Local time is: %s\n",asctime(tblock));
return 0;   
}

2. Convert time_t in C++ to DateTime in C# :


//time_t World time,   than   Local time   less 8 hours ( namely 28800 seconds )
double seconds = 1259666013 + 28800;
double secs = Convert.ToDouble(seconds);
DateTime dt = new DateTime(
1970, 1, 1, 0, 0, 0, DateTimeKind.Unspecified).AddSeconds(secs);
//TimeSpan span = 
//        TimeSpan.FromTicks(seconds*TimeSpan.TicksPerSecond); 
Console.WriteLine(dt);

3. Convert DateTime type of C# to time_t type of C++


public static long DateTimeToTime_t(DateTime dateTime)
{
long time_t;
DateTime dt1 = new DateTime(1970, 1, 1,0,0,0);
TimeSpan ts =dateTime - dt1;
time_t = ts.Ticks/10000000-28800;      
return time_t;
}
static void Main(string[] args)
{
DateTime dateTime = new DateTime(2009,12,1,19,13,33);
Console.WriteLine(DateTimeToTime_t(dateTime));
}


Related articles: