C++时间标准库时间time和系统时间的使用

1. C++标准库中的时间需要引用time.h,可以取的本地时间或者格林威治时间,只能精确到秒

#include <iostream>
 
/*包含time头文件*/
#include <time.h>
 
 
using namespace std;
 
int main()
{
    //time_t是long类型,精确到秒,是当前时间和1970年1月1日零点时间的差
    const time_t t = time(NULL);
 
    cout<<"current time is "<<t<<endl;
 
    /*本地时间:日期,时间 年月日,星期,时分秒*/
    struct tm* current_time = localtime(&t);
    printf("current year is %d;current month is %d;current date of month is %d\r\n",
        1900 + current_time->tm_year,
        1 + current_time->tm_mon/*此month的范围为0-11*/,
        current_time->tm_mday);
 
    printf("current day of year is %d;current day in week is %d\r\n",
        current_time->tm_yday,/*当前日期是今年的第多少天[0,365] */
        current_time->tm_wday/*days since Sunday - [0,6] */);
 
    printf("time part %d:%d:%d \r\n",
        current_time->tm_hour,
        current_time->tm_min,
        current_time->tm_sec);
 
    printf("\t本地时间:%d-%d-%d %d:%d:%d\r\n",
        current_time->tm_year + 1900,
        current_time->tm_mon + 1,
        current_time->tm_mday,
        current_time->tm_hour,
        current_time->tm_min,
        current_time->tm_sec);
 
    /*格林威治时间*/
    struct tm* current_gmtime = gmtime(&t);
 
    printf("格林威治时间:%d-%d-%d %d:%d:%d\r\n",
        current_gmtime->tm_year + 1900,
        current_gmtime->tm_mon + 1,
        current_gmtime->tm_mday,
        current_gmtime->tm_hour,
        current_gmtime->tm_min,
        current_gmtime->tm_sec);
 
 
    system("pause");
    return 0;
}

2. 系统时间 SYSTEMTIME 使用时要引用windows.h,可以精确到毫秒级别

#include <iostream>
#include <Windows.h>
 
 
int main(){
    //声明变量
    SYSTEMTIME sys_time;
 
    //将变量值设置为本地时间
    GetLocalTime( &sys_time );
 
    //输出时间
    printf( "%4d/%02d/%02d %02d:%02d:%02d.%03d 星期%1d\n",sys_time.wYear,
        sys_time.wMonth,
        sys_time.wDay,
        sys_time.wHour,
        sys_time.wMinute,
        sys_time.wSecond,
        sys_time.wMilliseconds,
        sys_time.wDayOfWeek);
 
    system("time");
 
    system("pause");
    return 0;
}

posted @   玉开  阅读(79672)  评论(2编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
历史上的今天:
2009-04-29 google网站地图的格式说明
2009-04-29 猪流感全面解析
2008-04-29 Sql Server2005对t-sql的增强之通用表表达式CTE
2008-04-29 Sql Server2005对t-sql的增强之top
点击右上角即可分享
微信分享提示