1:Date类型转换为字符串
Date date = DateUtil.date();
System.out.println("年月日" + DateUtil.formatDate(date));
System.out.println("时分秒" + DateUtil.formatTime(date));
System.out.println("年月日 时分秒" + DateUtil.formatDateTime(date));
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
String format1 = format.format(date);
System.out.println(format1);
2:字符串时间转Date
String strTime = "2020.10.10";
Date date = DateUtil.parse(strTime);
System.out.println("字符串转时间:" + date);
String strTime2 = "2020-10";
Date date2 = DateUtil.parse(strTime2,"yyyy-MM");
System.out.println("时间转字符串:" + date2);
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
try {
Date parse = format.parse("2022-03-31");
System.out.println(parse);
} catch (ParseException e) {
e.printStackTrace();
}
3:自定义一个时间工具类
import com.google.common.collect.Lists;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
public class DateUtils {
public static Date getStartDate(Date date) {
Calendar instance = Calendar.getInstance();
instance.setTime(date);
instance.set(Calendar.HOUR_OF_DAY, 0);
instance.set(Calendar.MINUTE, 0);
instance.set(Calendar.SECOND, 0);
return instance.getTime();
}
public static Date getEndDate(Date date) {
Calendar instance = Calendar.getInstance();
instance.setTime(date);
instance.set(Calendar.HOUR_OF_DAY, 23);
instance.set(Calendar.MINUTE, 59);
instance.set(Calendar.SECOND, 59);
return instance.getTime();
}
public static ArrayList<Date> getDayList(Integer intervals, Boolean flag) {
if (flag) {
ArrayList<Date> pastDaysList = Lists.newArrayList();
for (int i = 0; i < intervals; i++) {
pastDaysList.add(getPastDate(i));
}
return pastDaysList;
} else {
ArrayList<Date> futureDaysList = Lists.newArrayList();
for (int i = 0; i < intervals; i++) {
futureDaysList.add(getFutureDate(i));
}
return futureDaysList;
}
}
public static Date getPastDate(Integer past) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - past);
return calendar.getTime();
}
public static Date getFutureDate(Integer past) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) + past);
return calendar.getTime();
}
public static int differentDays(Date beforeDate, Date currentDate) {
Calendar cal1 = Calendar.getInstance();
cal1.setTime(beforeDate);
Calendar cal2 = Calendar.getInstance();
cal2.setTime(currentDate);
int day1 = cal1.get(Calendar.DAY_OF_YEAR);
int day2 = cal2.get(Calendar.DAY_OF_YEAR);
int year1 = cal1.get(Calendar.YEAR);
int year2 = cal2.get(Calendar.YEAR);
if (year1 != year2)
{
int timeDistance = 0;
for (int i = year1; i < year2; i++) {
if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0)
{
timeDistance += 366;
} else
{
timeDistance += 365;
}
}
return timeDistance + (day2 - day1);
} else
{
System.out.println("判断day2 - day1 : " + (day2 - day1));
return day2 - day1;
}
}
}
|