php中日期时间比较三个函数

文章介绍了三种常用的日期时间比较格式的函数,一个是对整日期,一个是只对时间比较,最后一个是专业比较时间差可以到秒。

日期比较如 2011-11-11 2011-12-12,代码如下:

  1. function compare_date( $DATE1, $DATE2 )
  2. {
  3. $STR = strtok( $DATE1, "-" );
  4. $YEAR1 = $STR;
  5. $STR = strtok( "-" );
  6. $MON1 = $STR;
  7. $STR = strtok( "-" );
  8. $DAY1 = $STR;
  9. $STR = strtok( $DATE2, "-" );
  10. $YEAR2 = $STR;
  11. $STR = strtok( "-" );
  12. $MON2 = $STR;
  13. $STR = strtok( "-" );
  14. $DAY2 = $STR;
  15. if ( $YEAR2 < $YEAR1 )
  16. {
  17. return 1;
  18. }
  19. if ( $YEAR1 < $YEAR2 )
  20. {
  21. return -1;
  22. }
  23. if ( $MON2 < $MON1 )
  24. {
  25. return 1;
  26. }
  27. if ( $MON1 < $MON2 )
  28. {
  29. return -1;
  30. }
  31. if ( $DAY2 < $DAY1 )
  32. {
  33. return 1;
  34. }
  35. if ( $DAY1 < $DAY2 )
  36. {
  37. return -1;
  38. }
  39. return 0;
  40. }

格式:12.00 -13.11,代码如下:

  1. function compare_time( $TIME1, $TIME2 )
  2. {
  3. $STR = strtok( $TIME1, ":" );
  4. $HOUR1 = $STR;
  5. $STR = strtok( ":" );
  6. $MIN1 = $STR;
  7. $STR = strtok( ":" );
  8. $SEC1 = $STR;
  9. $STR = strtok( $TIME2, ":" );
  10. $HOUR2 = $STR;
  11. $STR = strtok( ":" );
  12. $MIN2 = $STR;
  13. $STR = strtok( ":" );
  14. $SEC2 = $STR;
  15. if ( $HOUR2 < $HOUR1 )
  16. {
  17. return 1;
  18. }
  19. if ( $HOUR1 < $HOUR2 )
  20. {
  21. return -1;
  22. }
  23. if ( $MIN2 < $MIN1 )
  24. {
  25. return 1;
  26. }
  27. if ( $MIN1 < $MIN2 )
  28. {
  29. return -1;
  30. }
  31. if ( $SEC2 < $SEC1 )
  32. {
  33. return 1;
  34. }
  35. if ( $SEC1 < $SEC2 )
  36. {
  37. return -1;
  38. }
  39. return 0;
  40. }

格式:2011-11-12 1:6:25,2011-12-13 1:2:35,代码如下:

  1. function compare_date_time( $DATE_TIME1, $DATE_TIME2 )
  2. {
  3. if ( $DATE_TIME1 == NULL || strlen( $DATE_TIME1 ) == 0 || $DATE_TIME2 == NULL || strlen( $DATE_TIME2 ) == 0 )
  4. {
  5. return -1;
  6. }
  7. $DATE_TIME1_ARRY = explode( " ", $DATE_TIME1 );
  8. $DATE_TIME2_ARRY = explode( " ", $DATE_TIME2 );
  9. if ( compare_date( $DATE_TIME1_ARRY[0], $DATE_TIME2_ARRY[0] ) == 1 )
  10. {
  11. return 1;
  12. }
  13. if ( compare_date( $DATE_TIME1_ARRY[0], $DATE_TIME2_ARRY[0] ) == 0 )
  14. {
  15. if ( compare_time( $DATE_TIME1_ARRY[1], $DATE_TIME2_ARRY[1] ) == 1 )
  16. {
  17. return 1;
  18. }
  19. if ( compare_time( $DATE_TIME1_ARRY[1], $DATE_TIME2_ARRY[1] ) == 0 )
  20. {
  21. return 0;
  22. }
  23. return -1;
  24. }
  25. return -1;
  26. }