2016-10-21 12 views
-2

localtimeを使用して現在の日付を取得し、その後、ユーザーから日数を取得し、追加後の日付(月および日)を計算する将来の日付計算機を作成していますC++ int値を使用して日付を取得する方法

ここで、tm_mon/tm_mdayを適切に使用できるように、newDateのint値を使用して問題が発生しています。

unsigned int newDate; 

if (userInput > (365 - getDayOfYear())){ //If the intial date is greater than userInput 
     newDate = (userInput - (365 - getDayOfYear())); 
     cout << newDate << "\n"; 
    } 
    else if (userInput < (365 - getDayOfYear())) { //If the intial date is less than userInput 
     newDate = (getDayOfYear() + userInput); 
     cout << newDate << "\n"; 

time_t rawtime = NewDate; // The problem is over here 
    struct tm * timeinfo; 
    time(&rawtime); 
    timeinfo = localtime(&rawtime); 



    cout << "The date is "; 
    cout << monthArray[timeinfo->tm_mon] << " " ; 
    cout << dayArray[timeinfo->tm_mday] << "\n"; 

代替手段はありませんか?

+1

そして、あなたが苦しんでいる問題は何ですか?編集:さて、あなたはいくつかのコードをランダムに追加しました。ブレースはバランスが取れず、変数名は同じではありません。あなたは実際の問題が何であるかを言う必要があります。どのようにあなたの期待された出力とは異なる実際の出力が良いスタートです。 –

答えて

0

time()には、エポックからの現在の時間が秒単位で表示されます。だから、わずか数秒に変換し、将来的に日の所望の量を追加し、日と月を取得するためにlocaltime()を使用します。

time_t timer = time(nullptr); 
timer += days * 24 * 60 * 60l; 
tm *ptm = localtime(&timer); 
// print it 
1

ここでは、このheader-only open source libを使用してC++ 11/1Uでこれを使用して、これを行うための簡単な方法です:

#include "date.h" 
#include <iostream> 

int 
main() 
{ 
    using namespace date; 
    using namespace std::chrono; 
    auto currentDate = floor<days>(system_clock::now()); 
    auto diffDays = days{1000}; 
    auto futureDate = currentDate + diffDays; 
    std::cout << futureDate << '\n'; 
} 

現在出力:ここ

2019-07-18 

あなたは上記のコードを貼り付けとgccとCLAの様々なバージョンを使用して自分でそれを試してみることができますwandbox linkですng。

このコードは、最新のバージョンのVisual Studioでも実行されます。

自分でカレンダー計算を行う場合は、here are the underlying algorithms this library uses

関連する問題