概述
- 本文演示環境: 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;
}
輸出
