C++输出系统时间 日期带星期

180it 2020-10-09 AM 1767℃ 0条

编译软件:dev5.4.0
程序功能:输出系统时间,输出格式:2018-08-10 15:14:40
方法:使用time_t获取系统时间,再使用strftime()函数对日期和时间进行格式化
time_t time(time_t* t);

取得从1970年1月1日至今的秒数。

strftime()函数

size_t strftime(char str, size_t maxsize, const char format, const struct tm *timeptr)
参数说明:

str -- 这是指向目标数组的指针,用来复制产生的 字符串。
maxsize -- 这是被复制到 str 的最大字符数。
format -- 这是 C字符串,包含了普通字符和特殊格式说明符的任何组合。这些格式说明符由函数替换为表示 tm 中所指定时间的相对应值。格式说明符是:
例如:strftime(tmp, sizeof(tmp), "%Y-%m-%d %H:%M:%S",localtime(&timep) );

代码如下:

#include <iostream>
#include <string>
#include <time.h>
#include <stdlib.h>
using namespace std;
 
string getTime()
{
    time_t timep;
    time (&timep); //获取time_t类型的当前时间
    char tmp[64];
    strftime(tmp, sizeof(tmp), "%Y-%m-%d %H:%M:%S",localtime(&timep) );//对日期和时间进行格式化
    return tmp;
}
 
int main(){
    string   time = getTime();
    cout << time << endl;
    system("pause");
    return 0;
}

https://blog.csdn.net/cai_niaocainiao/article/details/81780520

#include <iostream>
#include <string>
#include <time.h>
#include <stdlib.h>
#include<windows.h>


using namespace std;

string getTime()
{
    time_t timep;
    time (&timep); //获取time_t类型的当前时间
    char tmp[64];
    strftime(tmp, sizeof(tmp), "%Y-%m-%d %H:%M:%S",localtime(&timep) );//对日期和时间进行格式化
    return tmp;
}

int main(){
    system("chcp 65001");
    string   time = getTime();
    cout << time << endl;


    string week = " ";
    while (1)
    {
        SYSTEMTIME systemTime;
        GetLocalTime(&systemTime);
        cout << "当前时间是:" << systemTime.wYear << "年" << systemTime.wMonth << "月" << systemTime.wDay << "日";
        cout << systemTime.wHour << "时" << systemTime.wMinute << "分" << systemTime.wSecond << "秒";
        switch (systemTime.wDayOfWeek)
        {
            case 0:
                week = "日";
                break;
            case 1:
                week = "一";
                break;
            case 2:
                week = "二";
                break;
            case 3:
                week = "三";
                break;
            case 4:
                week = "四";
                break;
            case 5:
                week = "五";
                break;
            case 6:
                week = "六";
                break;
        }
        cout << "   星期";
        cout << week << endl;
        Sleep(1000);
        system("cls");

    system("pause");
    }
    return 0;
}

支付宝打赏支付宝打赏 微信打赏微信打赏

如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!

标签: none

C++输出系统时间 日期带星期