从日期开始计算一年中的哪一天 [英] Calculating day of year from date

查看:73
本文介绍了从日期开始计算一年中的哪一天的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要计算给定日期的天数.一年有366天.但是,每个月都有一个不同的值,我必须指定这些值.有比我正在做的更快的方法吗?

I need to calculate the day number of a given date. The year has 366 days in it. Each month however has a different value and I have to assign the values. Is there a quicker way to do it rather than the way I am going about it?

#include<iostream>
using namespace std;
int main()
{
   int day, month, year, dayNumber;

   cout<< "Please enter the month, by numerical value:";
   cin>> month;
   cout<<"Please enter the day, by numerical value:";
   cin>> day;
   cout<<"Please enter the year, by numerical value:";
   cin>> year;
   if (month == 1)
   {
      dayNumber= day;
      cout<< "Month;" << '\t'<< month << '\n'
          << "Day:"<<'\t'<< day<< '\n'
          << "Year:"<<'\t'<< year<<'\n'
          << "Day Number:"<< '\t'<< dayNumber<< endl;
   }
   else if(month==2)
   {
      dayNumber= day+31; 
   }
}

推荐答案

在许多方面,最好避免手动滚动.

In many ways it is probably best to avoid hand-rolling this.

使用增强功能:

#include <boost/date_time/gregorian/gregorian.hpp>

//...
try {
    boost::gregorian::date d(year, month, day);
    dayNumber = d.day_of_year();
}
catch (std::out_of_range& e) {
    // Alternatively catch bad_year etc exceptions.
    std::cout << "Bad date: " << e.what() << std::endl;
}

正如James Kanze建议的那样,您也可以使用mktime来避免依赖boost(未经测试):

As James Kanze suggests you could also use mktime to avoid dependency on boost (untested):

  tm timeinfo = {};
  timeinfo.tm_year = year - 1900;
  timeinfo.tm_mon = month - 1;
  timeinfo.tm_mday = day;
  mktime(&timeinfo);
  dayNumber = timeinfo.tm_yday;

这篇关于从日期开始计算一年中的哪一天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆