简体   繁体   English

将时间戳转换为MYSQL_TIME

[英]Convert timestamp to MYSQL_TIME

I want to insert unix timestamp into MySQL using C library. 我想使用C库将unix时间戳插入MySQL。

According to MySQL doc , I should use MYSQL_TIME struct, like so: 根据MySQL doc ,我应该使用MYSQL_TIME结构,如下所示:

MYSQL_TIME  ts;

ts.year= 2002;
ts.month= 02;
ts.day= 03;

ts.hour= 10;
ts.minute= 45;
ts.second= 20;

What is the correct way to convert integer value that holds timestamp into this struct? 将持有时间戳的整数值转换为此结构的正确方法是什么?

Is there any solution other than pure parsing of the number? 除了单纯解析数字之外,还有其他解决方案吗?

This is my goal: 这是我的目标:

std::time_t t = 1534963754;
MYSQL_TIME mysql_time = convert_to_MYSQL_TIME(t);

My approach would be using localtime() which takes timer values in seconds and fills the tm structure. 我的方法是使用localtime() ,它以秒为单位获取计时器值并填充tm结构。 Use tm structure to fill MYSQL_TIME structure. 使用tm结构填充MYSQL_TIME结构。

definition of tm structure is tm结构的定义是

struct tm {
   int tm_sec;         /* seconds,  range 0 to 59          */
   int tm_min;         /* minutes, range 0 to 59           */
   int tm_hour;        /* hours, range 0 to 23             */
   int tm_mday;        /* day of the month, range 1 to 31  */
   int tm_mon;         /* month, range 0 to 11             */
   int tm_year;        /* The number of years since 1900   */
   int tm_wday;        /* day of the week, range 0 to 6    */
   int tm_yday;        /* day in the year, range 0 to 365  */
   int tm_isdst;       /* daylight saving time             */   
};

And your convert_to_MYSQL_TIME function will look like below. 您的convert_to_MYSQL_TIME函数将如下所示。

 MYSQL_TIME  convert_to_MYSQL_TIME(time_t t)
    {
       struct tm * timeinfo;
       MYSQL_TIME sqlTime;

       timeinfo = localtime (&t);
       sqlTime.year = timeinfo.tm_year;
       sqlTime.month = timeinfo.tm_mon;
       sqlTime.day = timeinfo.tm_mday;
       sqlTime.hour = timeinfo.tm_hour;
       sqlTime.minute = timeinfo.tm_min;
       sqlTime.second = timeinfo.tm_sec;

      return sqlTime;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM