话不多说,直接上代码。
package testDate;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
//项目案例 www.fhadmin.org
public class DateUtil {
private static String YYYY_MM_DD = "yyyy-MM-dd";
private static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
private static String YYYY_MM_DD_T_HH_MM_SS_SSS_Z = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
public static void main(String[] args) {
// 前一年
Date d1 = getLastNTime(Calendar.YEAR, -1);
System.out.println("前一年:" + DateToStr(d1, YYYY_MM_DD_HH_MM_SS));
// 后一天
Date d2 = getLastNTime(Calendar.DATE, 1);
System.out.println("后一天:" + DateToStr(d2, YYYY_MM_DD_HH_MM_SS));
// 转化为UTC时间
Date d3 = convertToUTC(new Date());
System.out.println("UTC时间:" + DateToStr(d3, YYYY_MM_DD_T_HH_MM_SS_SSS_Z));
// 获取当前月最后一天
Date d4 = getCurrentMonthLastDay();
System.out.println("当前月最后一天:" + DateToStr(d4, YYYY_MM_DD));
// 获取当前月天数
System.out.println("当前月天数:" + getCurrentMonthDayCount());
// 获取当前年天数
System.out.println("当前年天数:" + getCurrentYearDayCount());
}
/**
* 获取当前时间的后n时间(年/月/日...)
* @param timeType 时间类型(年/月/日...)
* @param n
* @return
*/
private static Date getLastNTime(int timeType, int n){
Calendar c = Calendar.getInstance();
c.add(timeType, n);
return c.getTime();
}
/**
* 转化为UTC时间
* @param date
* @return
*/
private static Date convertToUTC(Date date){
Calendar c = Calendar.getInstance();
c.setTime(date);
// 时间偏移量
int zoneOffset = c.get(Calendar.ZONE_OFFSET);
// 夏令时差
int dstOffset = c.get(Calendar.DST_OFFSET);
// 从时间里扣除这些差量,即可以取得UTC时间
c.add(Calendar.MILLISECOND, -(zoneOffset + dstOffset));
return c.getTime();
}
/**
* 获取当前月最后一天
* @return
*/
private static Date getCurrentMonthLastDay(){
Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH));
return c.getTime();
}
/**
* 获取当前月天数
* @return
*/
private static int getCurrentMonthDayCount(){
Calendar c = Calendar.getInstance();
return c.getActualMaximum(Calendar.DAY_OF_MONTH);
}
/**
* 获取当前年天数
* @return
*/
private static int getCurrentYearDayCount(){
Calendar c = Calendar.getInstance();
return c.getActualMaximum(Calendar.DAY_OF_YEAR);
}
/**
* 格式化时间
* @param date
* @param formatType
* @return
*/
private static String DateToStr(Date date, String formatType){
SimpleDateFormat sdf = new SimpleDateFormat(formatType);
return sdf.format(date);
}
}