输入当前日期,获取下一天的日期

      C可通过time()函数获取当前系统时间,返回的结果是一个time_t类型,其实就是一个大整数,其值表示CUT (Coordinated Universal Time)时间1970年1月1日00:00:00(称为UNIX系统的Epoch时间)到当前时刻的秒数。如下面的函数实现了将Epoch时间到当前的天数以字符的形式存放到四字节的数组中。
#define X 86400  //一天的总秒数
#include <time.h> 
#include <stdio.h>  

void utctime(unsigned char * p_str)
{
	time_t tmpcal_ptr, daytmpcal;
	
	struct tm *tmp_ptr = NULL;

	time(&tmpcal_ptr); 
	daytmpcal = tmpcal_ptr  / X;             //Epoch时间距当前的总天数

	p_str[0] = daytmpcal >> 24;             
	p_str[1] = daytmpcal >> 16;
	p_str[2] = daytmpcal >> 8;
	p_str[3] = daytmpcal;
	
	return ;
}

      上述程序只能唯一获取当前的时间标志,若需要获取指定某一天的时间,可以给函数增加一个参数days,让daytmpcal+days,但这样的话不同时刻调用该函数,days的取值不同。

      下面的程序实现了已知当前日期,获取下一天(或指定多少天以后)的日期的功能。

#include <stdio.h>  


unsigned char days_of_month[] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
unsigned char days_of_month_sSpecial[] = { 0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };


int isSpecialYear(int x) {
	if (x % 400 == 0 || (x % 4 == 0 && x % 100 != 0)) {
		return 1;
	}
	return 0;
}

int get_days(int year, int month)
{
	if (isSpecialYear(year) == 1)
	{
		return(days_of_month_sSpecial[month]);
	}
	else
	{
		return(days_of_month[month]);
	}
}

void get_next_day(unsigned char* p_today, unsigned char* p_tomorrow)
{
	//p_today[0] = year-2000; p_today[1] = month, p_today[2] = day;
	int year, month, day;
	year = (int)(p_today[0]) + 2000;
	month = (int)(p_today[1]);
	day = (int)(p_today[2]);

	day++;

	if (day > get_days(year, month))
	{
		day = 1;
		month++;

		if (month > 12)
		{
			month = 1;
			year++;
		}
	}

	p_tomorrow[0] = (unsigned char)(year - 2000);
	p_tomorrow[1] = (unsigned char)(month);
	p_tomorrow[2] = (unsigned char)(day);
	p_tomorrow[3] = p_today[3];


}

static unsigned char start_day[4] = {17, 12, 1, 0};

void ndayslater(unsigned char * p_str, int days)
{
	unsigned char next_day[4], today_day[4];
	memcpy(today_day, start_day, 4);
	int i;

	for (i = 0; i < days; i++)
	{
		get_next_day(today_day, next_day);

		memcpy(today_day, next_day, 4);
	}

	memcpy(p_str, today_day, 4);
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值