C语言 获取时间戳及格式化时间(毫秒级)
·
c语言获取时间戳和格式化时间
直接上代码
#include <stdio.h>
#include <sys/time.h>
#include <string.h>
#include <time.h>
long long get_timestamp(void)//获取时间戳函数
{
long long tmp;
struct timeval tv;
gettimeofday(&tv, NULL);
tmp = tv.tv_sec;
tmp = tmp * 1000;
tmp = tmp + (tv.tv_usec / 1000);
return tmp;
}
void get_format_time_string(char *str_time) //获取格式化时间
{
time_t now;
struct tm *tm_now;
char datetime[128];
time(&now);
tm_now = localtime(&now);
strftime(datetime, 128, "%Y-%m-%d %H:%M:%S", tm_now);
printf("now datetime : %s\n", datetime);
strcpy(str_time, datetime);
}
int main()
{
char *format_time_string[128] = {0};
long long curr_time = (long long)get_timestamp();
get_format_time_string((char *)format_time_string);
printf("timestamp:%lld, format time:%s",curr_time,format_time_string);
return 0;
}
PS:localtime_s是线程安全的,优于localtime
时间戳转换成格式字符串
#include <stdio.h>
#include <time.h>
void get_format_time_st(time_t t, char *pcTime)
{
struct tm *tm_t;
tm_t = localtime(&t);
strftime(pcTime,128,"%FT%T+0800",tm_t);
}
int main(void) {
unsigned long long curr_time = 1610617450;
char time_str[256] = {0};
time_t time = (time_t)curr_time;
get_format_time_st(time, (char *)time_str);
printf("%s",time_str);
return 0;
}
结果输出:2021-01-14T09:44:10+0800
获取毫秒级时间格式
void get_format_time_ms(char *str_time) {
struct tm *tm_t;
struct timeval time;
gettimeofday(&time,NULL);
tm_t = localtime(&time.tv_sec);
if(NULL != tm_t) {
sprintf(str_time,"%04d-%02d-%02d %02d:%02d:%02d.%03ld",
tm_t->tm_year+1900,
tm_t->tm_mon+1,
tm_t->tm_mday,
tm_t->tm_hour,
tm_t->tm_min,
tm_t->tm_sec,
time.tv_usec/1000);
}
return;
}
输出结果:2022-07-26 11:32:38.653
格式化时间转换成时间戳
long long format_time_to_timestamp() {
struct tm timeinfo;
time_t timestamp;
// 设置时间信息 这里示例 2023/08/08 17:43:11
timeinfo.tm_year = 2023 - 1900; // 年份需要减去1900
timeinfo.tm_mon = 8 - 1; // 月份是从0开始的,所以需要减去1
timeinfo.tm_mday = 8; // 日
timeinfo.tm_hour = 17 - 8; // 时
timeinfo.tm_min = 43; // 分
timeinfo.tm_sec = 11; // 秒
// 转换为时间戳
timestamp = mktime(&timeinfo);
printf("ts :%ld\n", timestamp);
return timestamp;
}
输出结果:
ts :1691487791
在线时间戳转换网站验证
更多推荐
已为社区贡献2条内容
所有评论(0)