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

本文通过C++代码展示了如何使用time函数获取当前时间戳,并利用localtime与gmtime函数将时间戳转换为本地时间和格林威治时间。同时,还介绍了如何通过Windows API获取更详细的系统时间。
#include <iostream>
#include <time.h>
#include <stdio.h>
#include <windows.h>

using namespace std;

int main()
{
    printf("%s","[time函数]\n");
       //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("本地时间:%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);

    cout <<'\n'<<endl;
    cout <<'\n'<<endl;

    printf("%s","[系统时间]\n");

    //声明变量
    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;
}

 

转载于:https://www.cnblogs.com/webcyz/p/3421585.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值