import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.TimeZone;
public class DateTimeUtil {
public static int getMonth(Date date) {
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
return calendar.get(Calendar.MONTH)+1;
}
public static String getMonth2(Date date) {
int month = getMonth(date);
if(month<10) {
return "0"+month;
}else {
return ""+month;
}
}
public static int getDay(Date date) {
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
return calendar.get(Calendar.DATE);
}
public static String getDay2(Date date) {
int day = getDay(date);
if(day<10) {
return "0"+day;
}else {
return ""+day;
}
}
public static int getHour(Date date) {
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
return calendar.get(Calendar.HOUR_OF_DAY);
}
public static int getYear(Date date) {
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
return calendar.get(Calendar.YEAR);
}
public static int getEndDay(int year,int month) {
if(month == 1||month == 3||month == 5||month == 7||month == 8||month == 10||month == 12) {
return 31;
}else if(month == 4||month == 6||month == 9||month == 11){
return 30;
}else if(month == 2) {
if((year%400 == 0) || (year%4 == 0 && year%100 != 0 )){
return 29;
}else {
return 28;
}
}
return 30;
}
public static Date parseDateFromCST(String time) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone("GMT+8"));
return sdf.parse(time);
}
/**
* 根据日期获取 星期 (2019-05-06 ——> 星期一)
* @param datetime
* @return
*/
public static int dateToWeek(String datetime) {
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
int[] weekDays = {7, 1, 2, 3, 4, 5, 6};
Calendar cal = Calendar.getInstance();
Date date;
try {
date = f.parse(datetime);
cal.setTime(date);
} catch (ParseException e) {
e.printStackTrace();
}
//一周的第几天
int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
if (w < 0)
w = 0;
return weekDays[w];
}
public static Date datetimeCalculate(Date inputDatetime, int unit, int count) {
Calendar calendar = new GregorianCalendar();
calendar.setTime(inputDatetime);
calendar.add(unit,count);
return calendar.getTime();
}
}