使用C标准库
相关日期、时间函数见C/C++ 日期 & 时间 函数总结
#include <stdio.h> /* printf, scanf */
#include <time.h>
using namespace std;
#pragma warning( disable : 4996 )
#include <iostream>
int main()
{
time_t rawtime;
struct tm* timeinfo;
char buffer[80];
time(&rawtime);
timeinfo = localtime(&rawtime);
printf("当前时间: %s", asctime(timeinfo));
//格式化时间
strftime(buffer, 80, "%Y-%m-%d %H:%M:%S", timeinfo);
std::cout <<"24小时制时间 " << buffer << std::endl;
//转换为12小时制
strftime(buffer, 80, "%Y-%m-%d %I:%M:%S", timeinfo);
std::cout <<"12小时制日期时间 " << buffer << std::endl;
strftime(buffer, 80, "%I:%M:%S %p", timeinfo);
std::cout << "12小时制时间 " << buffer << std::endl;
return 0;
}
也可以自己写24小时制转12小时制时间函数,如下:
/**
* 转换为12小时格式
* @param str 24小时制时间字符串 如 08:59:07 或者 20:59:07
* @return 12小时制的时间格式
*/
string convert_12hour(string str) {
string time;
int h1 = (int) str[0] - '0';
int h2 = (int) str[1] - '0';
int hh = h1 * 10 + h2;
//找到扩展名
string Meridien;
if (hh < 12) {
Meridien = "AM";
} else
Meridien = "PM";
hh %= 12;
if (hh == 12) {
time += "12";
for (int i = 2; i < 8; ++i) {
cout << str[i];
}
} else if (hh == 24) {
time = "00";
for (int i = 2; i < 8; ++i) {
time += str[i];
}
} else {
string h = to_string(hh);
time += h;
for (int i = 2; i < 8; ++i) {
time += str[i];
}
}
return time += " " + Meridien;
}
windows API
#include <stdio.h> /* printf, scanf */
#include <time.h>
using namespace std;
#pragma warning( disable : 4996 )
#include <iostream> /*cout*/
#include <windows.h>
//可以精确到毫秒
int main()
{
SYSTEMTIME sys;
GetLocalTime(&sys);
printf("%4d/%02d/%02d %02d:%02d:%02d.%03d 星期%1d\n", sys.wYear, sys.wMonth, sys.wDay, sys.wHour, sys.wMinute, sys.wSecond, sys.wMilliseconds, sys.wDayOfWeek);
char buf[128];
//重新赋值给字符串
sprintf(buf, "%4d-%02d-%02d %02d:%02d:%02d.%03d 星期%1d\n", sys.wYear, sys.wMonth, sys.wDay, sys.wHour, sys.wMinute, sys.wSecond, sys.wMilliseconds, sys.wDayOfWeek);
cout << "重新赋值给字符串" << buf << endl;
return 0;
}
利用系统函数,还能改动系统时间
#include <stdio.h> /* printf, scanf */
using namespace std;
#pragma warning( disable : 4996 )
#include <iostream> /*cout*/
#include<string>
#include <ctime>
int main()
{
system("time");
return 0;
}