2024-09-01
C/C++
00

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

默认计算2000年之后的,否则请改一下year_afer2000 那个地方。

默认计算间隔了多少分钟,若要计算秒钟,需要对应修改一下整体。

c
#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; }
如果对你有用的话,可以打赏哦
打赏
ali pay
wechat pay

本文作者:Dong

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 CC BY-NC。本作品采用《知识共享署名-非商业性使用 4.0 国际许可协议》进行许可。您可以在非商业用途下自由转载和修改,但必须注明出处并提供原作者链接。 许可协议。转载请注明出处!