您的位置:首页 > 编程语言 > C语言/C++

《C++--UTC时间ISO8601格式与本地时间转换》

2016-12-26 11:00 871 查看
做c/s开发,肯定要与时间打交道。

很多时候,获取本地的时间,也就是大陆境内的东八区时间。但是为了保证国际化,服务器往往采用的是0区的时间。

之前博客介绍了C++中关于时间的函数:

http://blog.csdn.net/wangshubo1989/article/details/50500515

首先明确几个概念:

UTC时间与GMT时间

Greenwich Mean Time (GMT) is a term originally referring to mean solar time at the Royal Observatory, Greenwich where a system was first developed around 1850 for tracking time based on the rotation of the Earth. It is now often used to refer to Coordinated Universal Time (UTC) when this is viewed as a time zone.

UTC与GMT的区别:



时间戳

时间戳是指格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00秒)起至现在的总秒数

本地时间

UTC + (+0800) = 本地(北京)时间

ISO8601

很多人问ISO8601与UTC的区别,其实两者完全是两个东西,通俗的说,iso8601是一种utc时间的表示方式而已。

例如:

2016-12-23T08:53:02.418Z


下面介绍几个结构体及函数:

std::tm

Structure holding a calendar date and time broken down into its components.

别忘了加入头文件:

<ctime>


std::get_time

When used in an expression in >> get_time(tmb, fmt), parses the character input as a date/time value according to format string fmt according to the std::time_get facet of the locale currently imbued in the input stream in. The resultant value is stored in a std::tm object pointed to by tmb.

别忘了加入头文件:

<iomanip>


_mkgmtime

Converts a UTC time represented by a tm struct to a UTC time represented by a time_t type.

strftime

Copies into ptr the content of format, expanding its format specifiers into the corresponding values that represent the time described in timeptr, with a limit of maxsize characters.

在之前的博客也有介绍,这里就不赘述了。

ISO8601格式转本地时间

std::string ISO8601ToLocaltime(const std::string& time)
{
struct std::tm time_struct;
std::istringstream ss(time);
ss >> std::get_time(&time_struct, "%Y-%m-%dT%H:%M:%SZ");
std::time_t time_unix = _mkgmtime(&time_struct);
if (time_unix == -1)
{
return "";
}
char current_time[32];
strftime(current_time, sizeof(current_time), "%Y-%m-%d %H:%M:%S", localtime(&time_unix));
std::string local_time_str(current_time);

return local_time_str;
}


本地时间转ISO8601格式

这里有两种写法,一种是最新的,适用于VS2015:

std::time_t course_start_time1 = 1483232400;
char buf[32];
strftime(buf, sizeof(buf), "%FT%TZ", gmtime(&course_start_time1));
std::cout << buf << std::endl;


另一种是适用于VS2013的:

std::string Win32Helper::LocaltimeToISO8601(std::time_t time)
{
char buf[32];
strftime(buf, sizeof(buf), "%Y-%m-%dT%H:%M:%SZ", gmtime(&time));
std::string iso8601_time_str(buf);

return iso8601_time_str;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: