c语言获取时间戳
时间: 2023-07-21 15:09:53 浏览: 60
在 C 语言中,你可以使用 time.h 头文件中的 time() 函数来获取当前时间的时间戳,其返回值为自1970年1月1日以来经过的秒数。
以下是获取时间戳的代码示例:
```c
#include <stdio.h>
#include <time.h>
int main() {
time_t timestamp = time(NULL);
printf("当前时间戳为: %ld\n", timestamp);
return 0;
}
```
在上述代码中,我们调用了 time() 函数并将返回值赋值给 timestamp 变量,然后通过 printf() 函数打印出当前时间戳。注意,time() 函数的参数为 NULL,表示获取当前时间的时间戳。
相关问题
c语言获取时间戳 并打印成年月日
可以使用 C 语言中的 time() 函数来获取当前时间戳,然后使用 localtime() 函数将时间戳转换为本地时间,最后使用 printf() 函数打印出年月日。下面是示例代码:
```c
#include <stdio.h>
#include <time.h>
int main() {
// 获取当前时间戳
time_t now = time(NULL);
// 将时间戳转换为本地时间
struct tm *local_time = localtime(&now);
// 打印年月日
printf("%04d-%02d-%02d\n", local_time->tm_year + 1900, local_time->tm_mon + 1, local_time->tm_mday);
return 0;
}
```
输出结果类似于:
```
2022-09-06
```
c语言获取时间戳 并打印成年月日.
可以使用 C 语言中的 time() 函数来获取当前时间戳,然后使用 localtime() 函数将时间戳转换为本地时间,最后使用 strftime() 函数将时间格式化成年月日的形式。下面是示例代码:
```c
#include <stdio.h>
#include <time.h>
int main() {
// 获取当前时间戳
time_t now = time(NULL);
// 将时间戳转换为本地时间
struct tm *local_time = localtime(&now);
// 格式化时间为年月日
char date_str[11];
strftime(date_str, sizeof(date_str), "%Y-%m-%d", local_time);
// 打印年月日
printf("%s\n", date_str);
return 0;
}
```
输出结果类似于:
```
2022-09-06
```