概述
- 本文演示环境: Windows10
- 使用C语言获取年月日时分秒毫秒,
代码
#include <iostream>
#include <string>
#include <time.h>
#include <sys/timeb.h>
using namespace std;
struct NowDate
{
char year_month_day_[16] = {0}; //年月日
char hour_minute_second_[16] = {0}; //时分秒
char mill_sec_[4] = {0}; //毫秒
};
/// 获取时间
NowDate getTime()
{
time_t timep;
time(&timep);
NowDate date;
strftime(date.year_month_day_, sizeof(date.year_month_day_), "%Y-%m-%d", localtime(&timep));
strftime(date.hour_minute_second_, sizeof(date.hour_minute_second_), "%H:%M:%S", localtime(&timep));
struct timeb tb;
ftime(&tb);
sprintf(date.mill_sec_, "%d", tb.millitm);
return date;
}
int main()
{
NowDate time = getTime();
cout << "year-month-day:" << time.year_month_day_ << endl;
cout << "hour-minute-second" << time.hour_minute_second_ << endl;
cout << "mill-seconds" << time.mill_sec_ << endl;
system("pause");
return 0;
}
输出