【问题标题】:Get seconds until end of month in C++在 C++ 中获取到月底的秒数
【发布时间】:2015-09-24 10:35:03
【问题描述】:

我需要在 C++ 中获取到月底的时间间隔。是否有任何 C++ API 可以轻松为我做到这一点?

我需要启动一个计时器,该计时器将在下个月的第一天 00:00:00 时到期。为此,我需要计算时间间隔,即从现在到本月底的秒数。

【问题讨论】:

  • 查看<ctime> 标头。
  • 您是在寻找精确的输出还是合理的近似值?
  • 我需要启动一个计时器,该计时器将在下个月的第一天 00:00:00 时到期。为此,我需要计算时间间隔,即从现在到本月底的秒数。
  • Boost.DateTime 可以为您做很多事情。

标签: c++ time


【解决方案1】:

它相当直截了当。获取 现在 和当月最后一天之间number of days 的差异。然后获取the number of seconds in a day

现在你有the number of seconds till the end of the month,现在用the number of seconds right now so far today 减去它,你会得到the number of seconds until the end of the month

#include <time.h>
#include <iostream>
using namespace std;

int main(){

    int day1,month1,year1;
    int day2,month2,year2;
    int i,temp,DaysDiff=0;
    int month[]={31,28,31,30,31,30,31,31,30,31,30,31};
    int totalDiffDaysSecs=0;
    int nowSeconds=0;
    int expire=1000;

    time_t t = time(0);   // get time now
    struct tm * now = localtime( & t );

    cout<<"\n";
    day1=now->tm_mday;
    month1=(now->tm_mon + 1);
    year1=(now->tm_year + 1900);

    day2=31;
    month2=7;
    year2=2015;
    temp=day1;

    for(i=month1;i<month2+(year2-year1)*12;i++){
        if(i>12){
            i=1;
            year1++;
        }

        if(i==2){
            if(year1%4==0 && (year1%100!=0 || year1%400==0))
            month[i-1]=29;
          else
            month[i-1]=28;
        }

        DaysDiff=DaysDiff+(month[i-1]-temp);
        temp=0;

    }
    cout <<"Current Time = "<< now->tm_hour << ":" << now->tm_min << "."<<now->tm_sec<<"\n";
    cout <<"Today's date   "<< (now->tm_year + 1900) << '-' << (now->tm_mon + 1) << '-'   <<  now->tm_mday << " \n";
    cout <<"Target  date   "<< year2 << '-' << month2 << '-'   <<  day2 << " \n";

    DaysDiff=DaysDiff+day2-temp;

    cout<<"Target Month = "<<i<<"\n";
    cout<<"Days in Target month = "<<month[i-1]<<"\n";
    cout<<"Days diff Today - Target Month = "<<DaysDiff<<" \n";

    totalDiffDaysSecs=DaysDiff*24*60*60; 

    nowSeconds= (now->tm_hour  * 3600) + (now->tm_min * 60)+ now->tm_sec;

    cout<<"Total seconds in a day = "<<24*60*60<<" \n";
    cout<<"current total seconds so far today = "<< nowSeconds <<"\n";

    cout<<"Total number of seconds in "<< DaysDiff <<" days = "<< totalDiffDaysSecs <<"\n";
    cout<<"\n\n";

    while(expire>0){

       t = time(0);   // get time now
       now = localtime( & t ); 

       nowSeconds= (now->tm_hour  * 3600) + (now->tm_min * 60)+ now->tm_sec;

       expire=totalDiffDaysSecs - nowSeconds;

       cout <<"Seconds until end of month = "<< expire <<"   \r";   
    }


    cout<<"\n\n";
    cout<<"Countdown expired.\n\n";
return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-30
    • 1970-01-01
    • 2010-12-13
    • 2011-10-15
    • 2020-07-14
    • 2015-02-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多