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

来源:互联网 发布:java中的private 编辑:程序博客网 时间:2024/06/06 02:11
      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);}