1,获取指定格式的当前日期,pattern可以是任意格式的日期,如"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm",
"yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm, HH:mm:ss"
public static String getDate(String pattern) {
return DateFormatUtils.format(new Date(), pattern);
}
2,日期格式转换
public static String formatDateTime(Date date,String pattern) {
return formatDate(date,pattern);
}
3,获取过去的分钟数(天数)
public static long pastMini(Date date) {
long t = System.currentTimeMillis() - date.getTime();
return t/(60*1000);
}
4,根据年月获取对应月份的天数
public static int getDaysByYearMonth(int year, int month) {
Calendar a = Calendar.getInstance();
a.set(Calendar.YEAR, year);
a.set(Calendar.MONTH, month - 1);
a.set(Calendar.DATE, 1);
a.roll(Calendar.DATE, -1);
int maxDate = a.get(Calendar.DATE);
return maxDate;
}
5,两个时间相差距离多少天多少小时多少分多少秒
public static long[] getDistanceTimes(Date startDate, Date endDate) {
long day = 0;
long hour = 0;
long min = 0;
long sec = 0;
long time1 = startDate.getTime();
long time2 = endDate.getTime();
long diff ;
if(time1<time2) {
diff = time2 - time1;
} else {
diff = time1 - time2;
}
day = diff / (24 * 60 * 60 * 1000);
hour = (diff / (60 * 60 * 1000) - day * 24);
min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
sec = (diff/1000-day*24*60*60-hour*60*60-min*60);
long[] times = {day, hour, min, sec};
return times;
}
6,获取当前日期多少天以前的日期字符串
public static String getBeforeDay(int day){
Calendar calendar = Calendar.getInstance(); //得到日历
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
calendar.add(Calendar.DATE, -day);
String days_ago = sdf.format(calendar.getTime());
return days_ago;
}
7,获取当前日期多少天以后的日期字符串
public static String getAfterDay(int day){
Calendar calendar = Calendar.getInstance(); //得到日历
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
calendar.add(Calendar.DATE, day);
String days_after = sdf.format(calendar.getTime());
return days_after;
}
8,字符串型日期转换成另一种格式的日期型字符串
/** * 字符串型日期转换成另一种格式的日期型字符串 * @param date * @param pattern * @return */ public static String stringToString(String date,String pattern) { SimpleDateFormat sdf = new SimpleDateFormat(pattern); try { Date d=sdf.parse(date); return sdf.format(d); } catch(ParseException px) { px.printStackTrace(); } return date; }