3.练习_Date类: 定义一个日期工具类DateUtil,实现将Date转换为String,将String转换为Date,计算日期的下一天,计算两个日期间相关的天数,获取日期中的年月日时分秒,代码
学习:第3遍
代码:
定义一个日期工具类DateUtil,实现以下的功能
1.将Date转换为String
2.将String转换为Date
3.计算日期的下一天
4.计算两个日期间相关的天数
5.获取日期中的年、月、日、时、分、秒
public class DateUtil {
public static final int YEAR = 0;
public static final int MONTH = 1;
public static final int DATE = 2;
public static final int HOUR = 3;
public static final int MINUTE = 4;
public static final int SECOND = 5;
private static final String Date = null;
/**
* 方法名:toString(Date date,String pattern)
* 方法功能:<将Date转换为String>
* 参数1:date
* 参数2:pattern:指定字符串的格式
* 返回值类型:String
*/
public static String toString(Date date,String pattern){
SimpleDateFormat df = new SimpleDateFormat(pattern);
String dateStr = df.format(date);
return dateStr;
}
/**
* 方法名:toString(Date date)
* 方法功能:调用了别的toString()方法
* <将Date转换为String,默认格式为yyyy-MM-dd HH:mm:ss>
* 参数1:date
* 返回值类型:String
*/
public static String toString(Date date){
String str = toString(date,"yyyy-MM-dd HH:mm:ss");
return str;
}
/**
* 方法名:toDate(String string, String pattern)
* 方法功能:将字符串解析为Date对象
* 参数1:string
* 参数1:pattern:字符串格式
* 返回值类型:Date
*/
public static Date toDate(String string, String pattern)
throws ParseException {
DateFormat df = new SimpleDateFormat(pattern);
Date date = (Date) df.parse(string);
return date;
}
/**
* 方法名:toDate(String string)
* 方法功能:将字符串解析为Date对象,默认格式为yyyy-MM-dd HH:mm:ss
* 参数1:string
* 返回值类型:Date
*/
public static Date toDate(String string) throws ParseException {
Date date2 = toDate(string, "yyyy-MM-dd HH:mm:ss");
return date2;
}
/**
* 方法名:Date getNextDay(Date date)
* 方法功能:计算日期的下一天
* 参数:date
* 返回值类型:Date
*/
public static Date getNextDay(Date date) {
long time = date.getTime() + 24 * 60 * 60 * 1000;
Date dateTommorrow = new Date(time);
return dateTommorrow;
}
/**
* 方法名:int getDuringDays(Date startDate, Date endDate)
* 方法功能:计算两个日期间相关的天数
* 参数1:startDate
* 参数2:endDate
* 返回值类型:int
*/
public static int getDuringDays(Date startDate, Date endDate) {
int days = 0;
while (startDate.before(endDate)) {
startDate = getNextDay(startDate);
days++;
}
return days;
}
/**
* 方法名:int get(Date date, int field)
* 方法功能:获取日期中的年、月、日、时、分、秒
* 参数1:date
* 参数2:field
* 返回值类型:int
*/
public static int get(Date date, int field) {
String s = toString(date);
String[] arr = s.split("-|\\s|:");
return Integer.parseInt(arr[field]);
}
}
public class Test {
public static void main(String[] args) throws ParseException {
Date date = new Date();
System.out.println(DateUtil.toString(date, "yyyy年MM月dd日 E"));
System.out.println(DateUtil.toString(date));
String string="2/14/2019 12:30:25";
Date date2 = DateUtil.toDate(string, "MM/dd/yyyy HH:mm:ss");
System.out.println(date2);
System.out.println(DateUtil.getNextDay(date));
System.out.println(DateUtil.getDuringDays(date2, date));
System.out.println(DateUtil.get(date, DateUtil.MONTH));
System.out.println(DateUtil.get(date, DateUtil.MINUTE));
}
}