import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
public class DateUtils {
public static long pastDays(Date date) {
long t = System.currentTimeMillis()-date.getTime();
return t/(24*60*60*1000);
}
public static String format(Date date) {
return format(date, "yyyy-MM-dd HH:mm:ss");
}
public static String formatToShortDate(Date date) {
return format(date, "yyyy-MM-dd");
}
public static String format(Date date, String format) {
if(date == null){
return "";
}
return new SimpleDateFormat(format).format(date);
}
public static String format(Date date, String format, Locale locale) {
return new SimpleDateFormat(format,locale).format(date);
}
public static Date parse(String str) throws ParseException {
return parse(str, "yyyy-MM-dd HH:mm:ss");
}
public static Date parse(String str, String format) throws ParseException {
return new SimpleDateFormat(format).parse(str);
}
public static String getDate() {
Date d = new Date();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
return format.format(d);
}
public static String getMonth() {
Date d = new Date();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
return format.format(d);
}
public static Date getDateByDayNum(Date date,int dayNum) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DATE, dayNum);
date = calendar.getTime();
return date;
}
public static long dateDiff(Date startTime, Date endTime) {
return endTime.getTime() - startTime.getTime();
}
public static Date getDateByHourNum(Date date,int hourNum){
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.HOUR_OF_DAY, hourNum);
date = calendar.getTime();
return date;
}
}
|