现在的位置: 首页 > 综合 > 正文

C++获得系统当前时间和日期

2018年04月13日 ⁄ 综合 ⁄ 共 6051字 ⁄ 字号 评论关闭

    最近想把实验程序运行过程中需要的一些实验信息保存到日志文件中,方便记录实验的结果和修改的参数,但是,每次文件的命名都是一个头痛的事情。因此,如何自动生成一个合适的名字一直是我想解决的问题,后面突然想起,可以使用程序运行的时间作为文件的名字,这样就知道是什么时候进行的实验了,同时,每次实验保存在不同的文件中,真是一个还可以的解决方案。




    

    想要获得系统的时间,有两个问题要解决:
1.如何获得系统当前的时间;
2.如何将系统当前的时间转化为能够作为文件名的字符串的形式。

    通过查找资料,知道可以通过C语言的标准库来实现,大部分函数都在time.h头文件中有声明。
    对于问题1,可以通过time函数来获得从1970年1月1日0时开始到目前为止经过的秒数,存储的格式为time_t;然后在使用localtime函数来将获得的秒数转化为当前系统的本地时间,储存的格式为tm*,需要注意的是,年份表示当前年份与1990年至今的差值。
    对于问题2,如果不考虑将时间作为文件名的话,是可以使用asctime函数将tm*类型保存的时间转换为字符串的,但是,转换出来的字符串包含有":"字符,在Windows下面不允许使用这样的字符作为文件名,因此,必须自己写函数,将保存在tm*类型中的时间信息读取出来,并形成自己需要的形式,我需要的时间为"y-m-d_h-m-s.log"。


   具体代码如下:
CurrentTime.h
#ifndef CURRENTTIME_H
#define CURRENTTIME_H

#include <time.h>
#include <string>

std::string GetCurrentTime();

std::string ConvertTimeToString(tm* Time);


#endif // CURRENTTIME_H



GetCurrentTime.cpp
/*M///////////////////////////////////////////////////////////////////////////
// Copyright (c) 2014, sheng
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright notice,
//       this list of conditions and the following disclaimer.
//
//     * Redistributions in binary form must reproduce the above copyright notice,
//       this list of conditions and the following disclaimer in the documentation
//       and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//M*/



#include "CurrentTime.h"
#include "IntToString.h"


/**
 * @brief  GetCurrentTime Get the local curretn time in string
 * @return The string which represent the loacl current time
 * @author sheng
 * @date   2014-08-21
 * @version 0.1
 *
 * @history
 *     <author>       <date>         <version>        <description>
 *      sheng       2014-08-21          0.1         build the function
 *
 */
std::string GetCurrentTime()
{
    // get the seconds since 00:00 hours, Jan 1, 1970 UTC
    time_t Time = time(NULL);


    // convert the Time to the local time
    tm* LocalTime = localtime(&Time);


    // convert the loacl time to a string
    std::string CurrentInString = ConvertTimeToString(LocalTime);


    return CurrentInString;
}




/**
 * @brief ConvertTimeToString Convert the local current time to a string
 * @param Time The local current time
 * @return A string which represents the local current time
 *
 * @author sheng
 * @date   2014-08-21
 * @version 0.1
 *
 * @history
 *     <author>       <date>         <version>        <description>
 *      sheng       2014-08-21          0.1         build the function
 *
 *
 */
std::string ConvertTimeToString(tm* Time)
{
    std::string Result;

    if (Time)
    {
        // add the year
        Result += IntToString(Time->tm_year + 1900) + "-";

        // add the month
        Result += IntToString(Time->tm_mon + 1) + "-";

        // add the day
        Result += IntToString(Time->tm_mday) + "_";

        // add the hour
        Result += IntToString(Time->tm_hour) + "-";

        // add the minutes
        Result += IntToString(Time->tm_min) + "-";

        // add the seconds
        Result += IntToString(Time->tm_sec) + ".log";
    }

    return Result;
}

IntToString.h
#ifndef INTTOSTRING_H
#define INTTOSTRING_H

#include <iostream>
std::string IntToString(int value);

#endif // INTTOSTRING_H
IntToString.cpp
#include <iostream>
#include <sstream>
#include "IntToString.h"

/**
 * @brief   IntToString translating the int value to the string.
 * @param   value
 * @return  the string of the input value
 *
 * @author  sheng
 * @version 0.1  [build the function] [2013/12/18] [sheng]
 */


std::string IntToString(int value)
{
    std::ostringstream convert;
    convert << value;
    return convert.str();
}

Test_functions.cpp

/*M///////////////////////////////////////////////////////////////////////////
// Copyright (c) 2014, sheng
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright notice,
//       this list of conditions and the following disclaimer.
//
//     * Redistributions in binary form must reproduce the above copyright notice,
//       this list of conditions and the following disclaimer in the documentation
//       and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//M*/



#include "CurrentTime.h"
#include <iostream>
/**
 * @brief Test_GetCurrentTime Test the GetCurrentTime function.
 *
 * @author sheng
 * @date 2014-08-21
 * @version 0.1
 *
 * @history
 *     <author>       <date>         <version>        <description>
 *      sheng        2014-08-21         0.1         build the function
 *
 */
void Test_GetCurrentTime()
{
   std::cout << "The current time is " << GetCurrentTime() << std::endl;
}




/**
 * @brief Test_ConvertTimeToString Test the ConvertTimeToString function.
 *
 * @author sheng
 * @date 2014-08-21
 * @version 0.1
 *
 * @history
 *     <author>       <date>         <version>        <description>
 *      sheng        2014-08-21         0.1         build the function
 *
 */
void Test_ConvertTimeToString()
{
    std::cout << "The null tm is " << ConvertTimeToString(NULL) << std::endl;

    tm Time;
    std::cout << "The Time is " << ConvertTimeToString(&Time) << std::endl;

}
main.cpp
#include <iostream>

#include "CurrentTime.h"

void Test_GetCurrentTime();
void Test_ConvertTimeToString();

using namespace std;

int main()
{
    cout << "Hello World!" << endl;

    Test_ConvertTimeToString();

    Test_GetCurrentTime();

    return 0;
}







github地址:https://github.com/shengno/GetCurrentTime

参考资料:







抱歉!评论已关闭.