<Boost> boost::lexical_cast字面转换和gregorian::date日期

lexical_cast

      用于字面值的转换,转换成int,double型,类似atoi函数。

gregorian::date

      是boost里面的日期时间,使用gregorian::date_duration进行日期的加减。

闰年

      涉及到日期,就有闰年的问题,关于闰年的解释如下:

      关于公历闰年是这样规定的:地球绕太阳公转一周叫做一回归年,一回归年长365日5时48分46秒。因此,公历规定有平年和闰年,平年一年有365日,比回归年短0.2422日,四年共短0.9688日,故每四年增加一日,这一年有366日,就是闰年。但四年增加一日比四个回归年又多0.0312日,400年后将多3.12日,故在400年中少设3个闰年,也就是在400年中只设97个闰年,这样公历年的平均长度与回归年就相近似了。由此规定:年份是整百数的必须是400的倍数才是闰年,例如1900年、2100年就不是闰年。

综上所述,我们可以得到:

     闰年即是4的倍数,同时不是100的倍数,或者是400的倍数的年份。


下面是我的代码:

#include <boost/date_time/gregorian/gregorian.hpp> 
#include <boost/lexical_cast.hpp> 
// (1)年份是4的倍数,但不是100的倍数
// (2)年份是400的倍数
bool is_leap_year(int year)
{
	return ( !(year%4) && ((year%100) || !(year%400)) );
}

int NumbericMonth(string month)
{
	string months[12] = {"Jan","Feb", "Mar","Apr","May","June",
						"July","Aug","Sep","Oct","Nov","Dec"};

	for (int i = 0; i < 12; i++)
	{
		if (_stricmp(months[i].c_str(), month.c_str()) == 0)
		{
			return i+1;
		}
	}
	return -1;
}
int NumbericDay(string day)
{
	string days[7] = {"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" };

	cout << day << " " ;
	for (int i = 0; i < 7; i++)
	{
		if (_stricmp(days[i].c_str(), day.c_str()) == 0)
		{
			return i+1;
		}
	}
	return -1;
}

void TestDate()
{
	//
	// lexical_cast 转换 
	int year = boost::lexical_cast<int>("2000");
	int month = boost::lexical_cast<int>("3");
	int day = boost::lexical_cast<int>("5");

	double sec = boost::lexical_cast<double>("53.234");
	cout << "Seconds: " << sec << endl;

	//
	// gregorian::date 日期
	boost::gregorian::date d(year, month, day); 
	std::cout << d.year() << "/"; 
	std::cout << NumbericMonth(boost::lexical_cast<string>(d.month())) << "/"; 
	std::cout << d.day() << std::endl; 
	std::cout << "End of month: " << d.end_of_month() << std::endl;  // 这个月的最后一天是几号

	boost::gregorian::date_duration dd(1);
	for (int i = 0; i < 7; i++)
	{
		d += dd;
		std::cout << NumbericDay(boost::lexical_cast<string>(d.day_of_week())) << std::endl;	// 星期几
	}

	std::cout << "After 7 days: " << d.year() << "/"; 
	std::cout << d.month() << "/"; 
	std::cout << d.day() << std::endl; 
	std::cout << "leap year: " << is_leap_year(d.year()) << endl;

	
}

程序运行结果:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值