You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
package com.jiudian.manage.until ;
import java.text.ParseException ;
import java.text.SimpleDateFormat ;
import java.util.Calendar ;
import java.util.Date ;
import java.util.GregorianCalendar ;
public class TimeUtil {
/**
* 计算两个日期之间的天数差( date2 - date1)
* @param date1 开始日期字符串( 格式: yyyy-MM-dd)
* @param date2 结束日期字符串( 格式: yyyy-MM-dd)
* @return 两个日期之间的天数差
*/
public static int getBetweenDay ( String date1 , String date2 ) {
// 将字符串日期转换为Calendar对象
Calendar d1 = new GregorianCalendar ( ) ;
d1 . setTime ( formatterTime ( date1 ) ) ;
Calendar d2 = new GregorianCalendar ( ) ;
d2 . setTime ( formatterTime ( date2 ) ) ;
int days = d2 . get ( Calendar . DAY_OF_YEAR ) - d1 . get ( Calendar . DAY_OF_YEAR ) ;
int y2 = d2 . get ( Calendar . YEAR ) ;
if ( d1 . get ( Calendar . YEAR ) ! = y2 ) {
do {
days + = d1 . getActualMaximum ( Calendar . DAY_OF_YEAR ) ;
d1 . add ( Calendar . YEAR , 1 ) ;
} while ( d1 . get ( Calendar . YEAR ) ! = y2 ) ;
}
return days ;
}
/**
* 将字符串日期格式化为Date对象
* @param date 日期字符串( 格式: yyyy-MM-dd)
* @return Date对象, 如果格式错误返回null
*/
public static Date formatterTime ( String date ) {
SimpleDateFormat formatter = new SimpleDateFormat ( "yyyy-MM-dd" ) ;
Date newDate = null ;
try {
newDate = formatter . parse ( date ) ;
} catch ( ParseException e ) {
e . printStackTrace ( ) ;
}
return newDate ;
}
}