C++システムの現在時刻と日付を取得

8412 ワード

最近、実験プログラムの実行中に必要ないくつかの実験情報をログファイルに保存し、実験の結果や修正パラメータを記録しやすくしたいと思っていますが、ファイルの命名は毎回頭が痛いことです.そのため、適切な名前をどのように自動的に生成するかはずっと私が解決したい問題で、後で突然思い出して、プログラムが実行できる時間をファイルの名前として使うことができて、このようにいつ行った実験かを知ることができて、同時に、毎回実験は異なるファイルの中で保存して、本当に1つの更に可能な解決策です.
    
システムを取得するには、次の2つの問題があります.
1.システムの現在の時間をどのように取得するか.
2.システムの現在の時間をファイル名として使用できる文字列の形式に変換する方法.
資料を探すことで、C言語の標準ライブラリで実現できることがわかり、ほとんどの関数はtime.hヘッダファイルに宣言があります.
問題1については、1970年1月1日0時から現在までの経過秒数をtime関数で得ることができ、記憶されているフォーマットは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
参考資料:
http://www.cplusplus.com/reference/ctime/time/?kw=time
http://www.cplusplus.com/reference/ctime/localtime/
http://www.cplusplus.com/reference/ctime/tm/
http://www.cplusplus.com/reference/ctime/gmtime/