时间转换为 HH:MM:SS 格式的字符串(C 编程)
我需要将“HH:MM:SS”格式的当前时间转换为字符数组(字符串),以便稍后可以使用 printf("%s", timeString);printf("%s", timeString);输出结果 顺便说一句,
我对 timeval
和 time_t
类型感到非常困惑,所以任何解释都会很棒:)
编辑: 所以我尝试了 strftime 等,它有点工作。这是我的代码:
time_t current_time;
struct tm * time_info;
char timeString[8];
time(¤t_time);
time_info = localtime(¤t_time);
strftime(timeString, 8, "%H:%M:%S", time_info);
puts(timeString);
但输出是这样的:“13:49:53a??J`aS?”
最后的“a??J`aS?”是怎么回事?
I need to get the current time in a "HH:MM:SS"-format into a character array (string) so I can output the result later simply with a printf("%s", timeString);
I'm pretty confused on the timeval
and time_t
types btw, so any explanation would be awesome:)
EDIT:
So I tried with strftime etc, and it kinda worked. Here is my code:
time_t current_time;
struct tm * time_info;
char timeString[8];
time(¤t_time);
time_info = localtime(¤t_time);
strftime(timeString, 8, "%H:%M:%S", time_info);
puts(timeString);
But the output is this: "13:49:53a??J`aS?"
What is going on with the "a??J`aS?" at the end?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您从这段代码中得到了垃圾:
因为您不允许在字符串上留有空终止符(\0)的空间,所以当它打印字符串时,它不知道结尾在哪里,并且会解释字符串中的随机垃圾。下一位内存作为字符串的一部分。
将其更改为:
它将正常工作,因为
strftime()
将有足够的空间来添加 \0。请注意,我使用 sizeof(array) 来避免忘记更改两个位置的数字的风险。You're getting garbage from this code:
Because you're not allowing space for a null terminator (\0) on the string, so when the string it printed, it doesn't know where the end is and inteprets random garbage in the next bit of memory as part of the string.
Change it to this:
And it'll work correctly because
strftime()
will have enough space to add a \0. Note that I'm using sizeof(array) to avoid the risk forgetting to change the number in both places.看一下 strftime 函数,它允许您将时间写入具有您选择的格式的字符数组。
Take a look at the strftime function, which allows you to write the time into a char array with a format of your choice.
处理时间的重要类型(时间的挂钟类型,而不是进程/线程时间)是
time_t
和struct tm
。对于某些工作,您可以在其中一种时间和另一种时间之间进行转换,但您必须注意本地时间与 UTC 时间。
仔细阅读
的说明
,尝试那里的函数,直到你在 C 中理解时间。再次,注意 UTC 时间和本地时间。
The important types for dealing with time (the wall-clock type of time, not process/thread time) are
time_t
andstruct tm
.With some work you can convert between one and the other, but you have to pay attention to local time versus UTC time.
Peruse the description of
<time.h>
, try the functions there until you grok time in C.Again, pay attention to UTC time and local time.