我有一个简单的C项目,我遇到了一个似乎无法解决的问题.注释掉这3行代码后,代码将产生以下正确结果:
1st Printing of Timestamp (UTC): 08/19/2023 15:04:48 (Unix Epoch time: 1692457488)
2nd Printing of Timestamp (UTC): 08/19/2023 15:04:48 (Unix Epoch time: 1692457488)
但是,如果我取消对这3行代码的注释,我会得到以下结果:
1st Printing of Timestamp (UTC): 08/19/2023 15:04:48 (Unix Epoch time: 1692457488)
2nd Printing of Timestamp (UTC): 08/19/2023 20:27:57 (Unix Epoch time: 1692457488)
其中"Second Print"产生present MM/DD/YYYY HH:MM:SS而不是正确的结果.Those 3 lines of code should have no effect在任何事情上-但他们确实这样做了,我看不到发生了什么.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
// Get a Unix epoch value
long long timestamp_ms = 1692457488113;
char formatted_time[50]; // only need 20 characters to hold "MM/DD/YYYY HH:MM:SS"
// Convert Unix timestamp to "MM/DD/YYYY HH:MM:SS" format in UTC time
time_t timestamp_seconds = (time_t)(timestamp_ms / 1000); // Convert milliseconds to seconds
struct tm *timestamp_timeinfo = gmtime(×tamp_seconds); // Use gmtime for UTC time
// print result - should be 08/19/2023 15:04:48 (Unix Epoch time: 1692457488)
strftime(formatted_time, sizeof(formatted_time), "%m/%d/%Y %H:%M:%S", timestamp_timeinfo);
printf("1st Printing of Timestamp (UTC): %s (Unix Epoch time: %lld)\n", formatted_time, timestamp_ms/1000);
/* time_t current_utc_time; // Get current UTC time grabbing variabluse I do nothing with (suspect gmtime memory leak)
time(¤t_utc_time);
struct tm *current_timeinfo = gmtime(¤t_utc_time);
*/
// print again, should be "08/19/2023 15:04:48 (Unix Epoch time: 1692457488)" but it is not
strftime(formatted_time, sizeof(formatted_time), "%m/%d/%Y %H:%M:%S", timestamp_timeinfo);
printf("2nd Printing of Timestamp (UTC): %s (Unix Epoch time: %lld)\n", formatted_time, timestamp_ms/1000);
return 0;
}