com.majiaxueyuan.util.DateUtil Maven / Gradle / Ivy
The newest version!
package com.majiaxueyuan.util;
import java.text.Format;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateUtil {
/**
* format Date to YYYYmmdd
*
* @param date date
*/
public static String formatYYYYMMDD(Date date) {
Format format = new SimpleDateFormat("yyyyMMdd");
String format2 = format.format(date);
return format2;
}
/**
* To Check date Is Today?
*
* @param date date
*/
public static boolean isToday(Date date) {
Calendar toCheckCalendar = Calendar.getInstance();
toCheckCalendar.setTime(date);
Calendar todayCalendar = Calendar.getInstance();
todayCalendar.setTimeInMillis(System.currentTimeMillis());
if (toCheckCalendar.get(Calendar.DATE) == todayCalendar.get(Calendar.DATE)) {
return true;
}
return false;
}
/**
* Get LastDay in WhichMonth
*
* @param yyyyMM eg:201903
* @throws ParseException
*/
public static Date getLastDate(String yyyyMM) throws ParseException {
SimpleDateFormat format2 = new SimpleDateFormat("yyyyMM");
Calendar ca = Calendar.getInstance();
ca.setTime(format2.parse(yyyyMM));
ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));
Date time = ca.getTime();
return time;
}
/**
* Get LastDay in WhichMonth
*
* @param thisDate thisDate
*/
public static Date getLastDate(Date thisDate) {
Calendar ca = Calendar.getInstance();
ca.setTime(thisDate);
ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));
Date time = ca.getTime();
return time;
}
/**
* Get FirstDay in WhichMonth
*
* @param yyyyMM eg 201903
*/
public static Date getFirstDate(String yyyyMM) throws ParseException {
SimpleDateFormat format2 = new SimpleDateFormat("yyyyMM");
Calendar c = Calendar.getInstance();
c.setTime(format2.parse(yyyyMM));
c.set(Calendar.DAY_OF_MONTH, 1);
return c.getTime();
}
/**
* Get FirstDay in WhichMonth
*
* @param thisDate thisDate
*/
public static Date getFirstDate(Date thisDate) {
Calendar c = Calendar.getInstance();
c.setTime(thisDate);
c.set(Calendar.DAY_OF_MONTH, 1);
return c.getTime();
}
/**
* Get days Between two Date
*
* @param startDate startDate
* @param endDate endDate
*/
public static int getBetweenDays(Date startDate, Date endDate) {
Calendar cal1 = Calendar.getInstance();
cal1.setTime(startDate);
Calendar cal2 = Calendar.getInstance();
cal2.setTime(endDate);
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) + 1;
} else {
return day2 - day1 + 1;
}
}
}