使用C语言计算两个日期之间间隔了多少分钟的程序

2023-05-16

使用C语言计算两个日期之间间隔了多少分钟的方法:

默认计算2000年之后的,否则请改一下year_afer2000 那个地方。
默认计算间隔了多少分钟,若要计算秒钟,需要对应修改一下整体。

#include <stdio.h>
//#include <stdlib.h>
//#include <ctype.h>
//#include <string.h>
//#include <stdio.h>
//#include <time.h>
unsigned long cal_total_min( int year, int month, int day, int hour, int minute )
{
    unsigned long	total_minutes1;
    unsigned long	total_minutes2;
    unsigned long	total_minutes3;
    unsigned long	total_minutes4;
    unsigned long	date1_minutes;
    int year_afer2000;
    int		i;
    int		month_days[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

    /* 计算日期1到日期2的总分钟数 */
    total_minutes1 = 0;
    year_afer2000 = year - 2000;                                /* 默认计算2000年之后的 */
    for ( i = 0; i < year_afer2000; i++ )
    {
        if ( (i % 4 == 0 && i % 100 != 0) || i % 400 == 0 )     /* 闰年 */
            total_minutes1 += 366 * 24 * 60;
        else
            total_minutes1 += 365 * 24 * 60;
    }

    total_minutes2 = 0;
    for ( i = 0; i < month - 1; i++ )
        if ( i == 1 )                                                           /* 2月 */
        {
            if ( (year % 4 == 0 && year % 100 != 0) || year % 400 == 0 )    /* 闰年 */
                total_minutes2 += 29 * 24 * 60;
            else
                total_minutes2 += 28 * 24 * 60;
        } else {
            total_minutes2 += month_days[i] * 24 * 60;
        }

    total_minutes3	= day * 24 * 60;
    total_minutes4	= hour * 60 + minute;
    date1_minutes	= total_minutes1 + total_minutes2 + total_minutes3 + total_minutes4;

    return(date1_minutes);
}


/* 计算两个日期相差多少分钟的绝对值,考虑每个月天数和闰年 */
unsigned long cal_two_time_diff( char *time1, char *time2 )
{
    int		year1, month1, day1, hour1, minute1;
    int		year2, month2, day2, hour2, minute2;
    unsigned long	date1_minutes;
    unsigned long	date2_minutes;

    sscanf( time1, "%4d%2d%2d%2d%2d", &year1, &month1, &day1, &hour1, &minute1 );
    sscanf( time2, "%4d%2d%2d%2d%2d", &year2, &month2, &day2, &hour2, &minute2 );

    date1_minutes	= cal_total_min( year1, month1, day1, hour1, minute1 );
    date2_minutes	= cal_total_min( year2, month2, day2, hour2, minute2 );

    /* 两个日期相差的绝对分钟数 */
    if ( date1_minutes > date2_minutes )
        return(date1_minutes - date2_minutes);
    else
        return(date2_minutes - date1_minutes);
}


int main() {
    unsigned long diff_minutes = cal_two_time_diff("202312312359", "200001010000");
    printf("两个日期相差的分钟数为:%lu\n", diff_minutes);

    return 0;
}



本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用C语言计算两个日期之间间隔了多少分钟的程序 的相关文章

随机推荐