温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C++时间与字符串如何转换

发布时间:2022-10-18 15:42:51 来源:亿速云 阅读:152 作者:iii 栏目:编程语言

今天小编给大家分享一下C++时间与字符串如何转换的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。

1. 1、常用的时间存储方式
2. 
3. 1)time_t类型,这本质上是一个长整数,表示从1970-01-01 00:00:00到目前计时时间的秒数,如果需要更精确一点的,可以使用timeval(time_t *t); //取得从1970年1月1日至今的秒数
24. char *asctime(const struct tm *tm); //将结构中的信息转换为真实世界的时间,以字符串的形式显示
25. char *ctime(const time_t *timep); //将timep转换为真是世界的时间,以字符串显示,它和asctime不同就在于传入的参数形式不一样
26. struct tm *gmtime(const time_t *timep); //将time_t表示的时间转换为没有经过时区转换的UTC时间,是一个struct tm结构指针
27. struct tm *localtime(const time_t *timep); //和gmtime类似,但是它是经过时区转换的时间。
28. time_t mktime(struct tm *tm); //将struct tm 结构的时间转换为从1970年至今的秒数
29. int gettimeofday(struct timeval(time_t time1, time_t time2); //返回两个时间相差的秒数
31. 
32. 
33. 3、时间与字符串的转换
34. 
35. 需要包含的头文件如下
36. 
37. #include <iostream>
38. #include <time.h>
39. #include <stdlib.h>
40. #include <string.h>
41. 
42. 1)unix/windows下时间转字符串参考代码
43. 
44. time_t t;  //秒时间
45. tm* local; //本地时间
46. tm* gmt;   //格林威治时间
47. char buf[128]= {0};
48. 
49. t = time(NULL); //获取目前秒时间
50. local = localtime(&t); //转为本地时间
51. strftime(buf, 64, "%Y-%m-%d %H:%M:%S", local);
52. std::cout << buf << std::endl;
53. 
54. gmt = gmtime(&t);//转为格林威治时间
55. strftime(buf, 64, "%Y-%m-%d %H:%M:%S", gmt);
56. std::cout << buf << std::endl;
57. 
58. 
59. 
60. 2)unix字符串转时间参考代码
61. 
62. 
63. tm tm_;
64. time_t t_;
65. char buf[128]= {0};
66. 
67. strcpy(buf, "2012-01-01 14:00:00");
68. strptime(buf, "%Y-%m-%d %H:%M:%S", &tm_); //将字符串转换为tm时间
69. tm_.tm_isdst = -1;
70. t_  = mktime(&tm_); //将tm时间转换为秒时间
71. t_ += 3600;  //秒数加3600
72. 
73. tm_ = *localtime(&t_);//输出时间
74. strftime(buf, 64, "%Y-%m-%d %H:%M:%S", &tm_);
75. std::cout << buf << std::endl;
76. 
77. 
78. 
79. 3)由于windows下没有strptime函数,所以可以使用scanf来格式化
80. 
81. 
82. time_t StringToDatetime(char *str)
83. {
84. tm tm_;
85. int year, month, day, hour, minute,second;
86. "%d-%d-%d %d:%d:%d", &year, &month, &day, &hour, &minute, &second);
87. tm_.tm_year  = year-1900;
88. tm_.tm_mon   = month-1;
89. tm_.tm_mday  = day;
90. tm_.tm_hour  = hour;
91. tm_.tm_min   = minute;
92. tm_.tm_sec   = second;
93. tm_.tm_isdst = 0;
94. 
95. time_t t_ = mktime(&tm_); //已经减了8个时区
96. return t_; //秒时间
97. }
98.

以上就是“C++时间与字符串如何转换”这篇文章的所有内容,感谢各位的阅读!相信大家阅读完这篇文章都有很大的收获,小编每天都会为大家更新不同的知识,如果还想学习更多的知识,请关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++
AI