time_t转换格式问题
time_t conversion format question
我正在尝试制作一个易于访问的TimeDate变量,但是在转换方面遇到了问题。在 time.h 中,如何将time_t(自 1970 年 1 月 1 日以来的秒数(转换为当前本地时区(如果适用,补偿夏令时(,以便:
time_t Seconds;
成为:
struct TimeDate
{
short YYYY;
unsigned char MM;
unsigned char DD;
unsigned char HH; //Non-DST, non-timezone, IE UTC (user has to add DST and TZO to get what they need)
unsigned char MM;
unsigned char S;
char TZ[4]; //This can be optionally a larger array, null terminated preferably
char TZO; //Timezone Offset from UTC
char DST; //Positive is DST (and amount of DST to apply), 0 is none, negative is unknown/error
};
在此过程中不使用任何字符串文字(时区名称的栏((以保持其效率(?这也考虑到了闰年。如果TimeDate可以转换回time_t,则奖金。
C 标准库(使用 ctime
在 C++ 中访问(提供了用于该目的的localtime
(或 UTC gmtime
(。如果标准结构不足以满足您的需求,您可以将生成的struct tm
硬塞到您自己的结构中。
没有提供的一件事是时区本身,但您可以通过将strftime
与%Z
和%z
格式字符串一起使用来获得它(以及ISO 8601格式的偏移量(
举个例子,这里有一个程序在实际中演示了这一点:
#include <iostream>
#include <cstdlib>
#include <ctime>
int main(void) {
time_t t;
struct tm *tim;
char tz[32];
char ofs[32];
std::system ("date");
std::cout << std::endl;
t = std::time (0);
tim = std::localtime (&t);
std::strftime (tz, sizeof (tz), "%Z", tim);
std::strftime (ofs, sizeof (ofs), "%z", tim);
std::cout << "Year: " << (tim->tm_year + 1900) << std::endl;
std::cout << "Month: " << (tim->tm_mon + 1) << std::endl;
std::cout << "Day: " << tim->tm_mday << std::endl;
std::cout << "Hour: " << tim->tm_hour << std::endl;
std::cout << "Minute: " << tim->tm_min << std::endl;
std::cout << "Second: " << tim->tm_sec << std::endl;
std::cout << "Day of week: " << tim->tm_wday << std::endl;
std::cout << "Day of year: " << tim->tm_yday << std::endl;
std::cout << "DST?: " << tim->tm_isdst << std::endl;
std::cout << "Timezone: " << tz << std::endl;
std::cout << "Offset: " << ofs << std::endl;
return 0;
}
当我在我的盒子上运行它时,我看到:
Wed Sep 28 20:45:39 WST 2011
Year: 2011
Month: 9
Day: 28
Hour: 20
Minute: 45
Second: 39
Day of week: 3
Day of year: 270
DST?: 0
Timezone: WST
Offset: +0800
相关文章:
- 警告处理为错误这里有什么问题
- 最小硬币更换问题(自上而下方法)
- 为"adjacent"变量赋值时出现问题
- 我的神经网络不起作用 [XOR 问题]
- 在Ubuntu 16.04上安装Cilk时出现问题
- 在用于格式4的arm模拟器中实现功能时的一个问题
- 格式说明符C++有什么问题
- DNS 查询格式标头结构中的小字节序问题
- TinyXML以及标签和格式问题
- 格式化二维数组的标准偏差代码时遇到问题
- 自定义图像格式的奇怪OpenCV问题
- c++输出格式问题
- 使用复制算法在 C++ 中打印矢量的格式问题
- 将军事时间转换为标准格式(HH:MM)并以标准格式计算平均值.三个问题
- C++括号和格式问题(未声明的标识符,本地函数定义是非法的)
- 结构格式问题,无法转换
- VS10 中文件名的正则表达式格式有什么问题<regex>?
- 与阅读不同格式的数字字符有关的问题
- Jsoncpp格式问题
- time_t转换格式问题