c++获取当前时间并格式化时间

使用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;
}

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值