涉及的核心類:Date類、SimpleDateFormat類、Calendar類
Date date = new Date();//取得當前時間Date類型
long date2long = date.getTime();//Date轉long
long cur = System.currentTimeMills();//取得當前時間long型返回
Date long2date = new Date(cur);//long轉Date
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");//設置目標轉換格式為yyyy-MM-dd HH:mm:ss.SSS
String date2string = sdf.format(date);//Date轉String
String str="2001-11-03 11:12:33.828";//設置初始string類型日期
Date str2date=sdf.parse(str);//String轉Date
Calendar cal = Calendar.getInstance();//取得當前時間Calendar類型
cal.setTime(date); //Date轉Calendar
Calendar cal = Calendar.getInstance();//取得當前時間Calendar類型
Date cal2date = cal.getTime();//Calendar轉Date
Q:寫一個方法,參數是Date date,將date往後推3天,在以“yyyy-mm-dd”格式返回字符串類型
public String add3Day(Date date) throws ParseException{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
cal.setTime(date);//Date轉換為Calendar
cal.add(Calendar.DATE, 3);//將日期往後推3天,減少3天則-3. 月增加則Calendar.MONTH
String after = sdf.format(cal.getTime());//Calendar轉換為Date,再轉換為String
return after;
}