使用strftime获取时间戳(Getting timestamp using strftime)

编程入门 行业动态 更新时间:2024-10-23 11:32:54
使用strftime获取时间戳(Getting timestamp using strftime)

我有时间在几秒钟内long tv_sec ,我想使用函数stftime使用格式%Y-%m-%d %X获得正确的日期和时间。 所以我有几秒钟的时间戳,我想用stftime转换它。

这是我的试用版

struct tm dateStruct; memset(dateStruct, 0, sizeof(struct tm)); gmtime(&timestampInSecs,dateStruct); char buffer[80]; strftime(buffer,80,"%Y-%m-%d %X", dateStruct); printf("Formatted date & time : |%s|\n", buffer );

I have time in seconds long tv_sec, and I want to get the correct date, and time, using the format %Y-%m-%d %X, using the function stftime. So I have the time stamps in seconds and I want to convert it using stftime.

This is my trial

struct tm dateStruct; memset(dateStruct, 0, sizeof(struct tm)); gmtime(&timestampInSecs,dateStruct); char buffer[80]; strftime(buffer,80,"%Y-%m-%d %X", dateStruct); printf("Formatted date & time : |%s|\n", buffer );

最满意答案

确保timestampInSecs是time_t类型并尝试这样:

char buffer[80]; strftime(buffer,80,"%Y-%m-%d %X", gmtime(&timestampInSecs)); printf("Formatted date & time : |%s|\n", buffer );

编辑

示例:如果您有timestampInSecs表示从2000年1月1日起的秒数,您必须使用从1/1/1970 (Linux time.h中的纪元)的所有秒来补偿变量。从1970年1月1日到1月1日我们有:

10957天 262968小时 946684800秒

最后,您必须将946684800总和为您的变量才能使用strftime ,如我的代码所示。

然后你必须做的是计算1/1/1970至你的开始日期和时间( timestampInSecs=0的日期和时间)之间的秒数

Ensure that timestampInSecs is time_t type and try this:

char buffer[80]; strftime(buffer,80,"%Y-%m-%d %X", gmtime(&timestampInSecs)); printf("Formatted date & time : |%s|\n", buffer );

EDIT

Example: if you have timestampInSecs that represent seconds from 1/1/2000 you must compensate the variable with all seconds from 1/1/1970 (epoch in Linux time.h) From 1/1/1970 to 1/1/2000 we have:

10957 days 262968 hours 946684800 seconds

At the end you have to sum 946684800 to your variable to be able to use strftime as shown in my code.

Then what you must do is to calculate seconds between 1/1/1970 and your start date and time (the date and time of timestampInSecs=0)

更多推荐

本文发布于:2023-04-27 14:32:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1327161.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:时间   strftime   timestamp

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!