时间处理速查手册

LocalDate
常用方法
LocalTime
常用方法
LocalDateTime
常用方法
方法示例
jodaTime
常用方法
java.util.date
常用方法
calender
常用方法
hutool
常用方法toc

LocalDate

常用方法

#取当前日期:
LocalDate today = LocalDate.now(); // -> 2014-12-24
#根据年月日取日期,12月就是12:
LocalDate crischristmas = LocalDate.of(2014, 12, 25); // -> 2014-12-25
#根据字符串取:
LocalDate endOfFeb = LocalDate.parse("2014-02-28"); // 严格按照ISO yyyy-MM-dd验证,02写成2都不行,当然也有一个重载方法允许自
#明年第一天
System.out.println(LocalDate.now().with(TemporalAdjusters.firstDayOfNextYear()));
己定义格式
LocalDate.parse("2014-02-29"); // 无效日期无法通过:DateTimeParseException: Invalid date
#取本月第1天:
LocalDate firstDayOfThisMonth = today.with(TemporalAdjusters.firstDayOfMonth()); // 2014-12-01
#取本月第2天:
LocalDate secondDayOfThisMonth = today.withDayOfMonth(2); // 2014-12-02
#取本月最后一天,再也不用计算是28,29,30还是31:
LocalDate lastDayOfThisMonth = today.with(TemporalAdjusters.lastDayOfMonth()); // 2014-12-31
#取下一天:
LocalDate firstDayOf2015 = lastDayOfThisMonth.plusDays(1); // 变成了2015-01-01
#取2015年1月第一个周一
LocalDate firstMondayOf2015 = LocalDate.parse("2015-01-01").with(TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY)); // 2015-01-05
#上个月第一天  
String maxRecordDate = LocalDate.now().minusMonths(1).with(TemporalAdjusters.lastDayOfMonth()).toString();
#获取某周的周一
String maxRecordDate = LocalDate.now().minusWeeks(1).with(DayOfWeek.MONDAY).toString();
#获取明天和昨天
LocalDate today = LocalDate.now();
LocalDate tomorrow = today.plus(1, ChronoUnit.DAYS);
LocalDate yesterday = tomorrow.minusDays(2);
#获取周几
LocalDate independenceDay = LocalDate.of(2014, Month.JULY, 4);
DayOfWeek dayOfWeek = independenceDay.getDayOfWeek();
System.out.println(dayOfWeek);// FRIDAY
#相隔多少天
LocalDate day1= LocalDate.of(2014, Month.JULY, 4);
LocalDate day2= LocalDate.of(2014, Month.JULY, 14);
int days = day2.toEpochDay() - day1.toEpochDay();
#获取年龄
LocalDate today = LocalDate.now();
System.out.println("Today : " + today);
LocalDate birthDate = LocalDate.of(1993, Month.OCTOBER, 19);
System.out.println("BirthDate : " + birthDate);
Period p = Period.between(birthDate, today);
System.out.printf("年龄 : %d 年 %d 月 %d 日", p.getYears(), p.getMonths(), p.getDays());
#通过时间戳获取一个月以后的时间
public static final DateTimeFormatter LONG_DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
Long localDateTime = LocalDateTime.now().plusMonths(1).toInstant(ZoneOffset.of("+8")).toEpochMilli();
System.out.println(FansBook.LONG_DATE_FORMATTER.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(localDateTime), ZoneId.systemDefault())));
#获取前一个小时的开始结束时间戳
final SimpleDateFormat longHourSdf = new SimpleDateFormat("yyyy-MM-dd HH");
final SimpleDateFormat longSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Long localDateTime = LocalDateTime.now().minusHours(1).toInstant(ZoneOffset.of("+8")).toEpochMilli();
try {
    Long hour_start = longHourSdf.parse(longHourSdf.format(localDateTime)).getTime();
    Long hour_end = longSdf.parse(longHourSdf.format(localDateTime) + ":59:59").getTime();
    System.out.println(hour_end);
    System.out.println(hour_start);
} catch (ParseException e) {
    e.printStackTrace();
}

LocalTime

常用方法

#LocalTime包含毫秒:
LocalTime now = LocalTime.now(); // 11:09:09.240
你可能想清除毫秒数:
LocalTime now = LocalTime.now().withNano(0)); // 11:09:09
构造时间也很简单:
LocalTime zero = LocalTime.of(0, 0, 0); // 00:00:00
LocalTime mid = LocalTime.parse("12:00:00"); // 12:00:00
#不同时区时间
ZoneId zone1 = ZoneId.of("Europe/Berlin");
ZoneId zone2 = ZoneId.of("Brazil/East");
System.out.println(zone1.getRules());
System.out.println(zone2.getRules());
#time
LocalTime now1 = LocalTime.now(zone1);
LocalTime now2 = LocalTime.now(zone2);
System.out.println(now1);
System.out.println(now2);
System.out.println(now1.isBefore(now2));

LocalDateTime

常用方法

#获取一天的开始和结束时间
LocalDateTime today_start = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);//当天零点
LocalDateTime today_end = LocalDateTime.of(LocalDate.now(), LocalTime.MAX);//当天零点
String td_st_str = today_start.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
String td_ed_str = today_end.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
System.out.println(td_ed_str);
#转时间戳
Long localDateTime = LocalDateTime.now().minusMinutes(5).toInstant(ZoneOffset.of("+8")).toEpochMilli();
#时间戳转LocalDateTime
Long remindTime = 1564638057304L;
LocalDateTime time2 =LocalDateTime.ofEpochSecond(remindTime/1000,0,ZoneOffset.ofHours(8));
System.out.println(time2);
#通过时间戳转换成LocalDateTime 并且计算与当前时间差值
DateTimeFormatter ftf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime localDateTime = LocalDateTime.parse(ftf.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(Long.valueOf("1560762892000")), ZoneId.systemDefault())),ftf);
LocalDateTime localDateTime1 = LocalDateTime.now();
Duration duration = java.time.Duration.between(localDateTime,localDateTime1);
System.out.println(duration.toHours());
#获取时间
public static final DateTimeFormatter SHORT_DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd");
String dateStr = LocalDateTime.now().format(SHORT_DATE_FORMATTER);//20191212

方法示例

public static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("HHmmss");
public static final DateTimeFormatter MONTH_FORMATTER = DateTimeFormatter.ofPattern("yyyyMM");
public static final DateTimeFormatter SHORT_DATE_FORMATTER = DateTimeFormatter.ofPattern("yyMMdd");
public static final DateTimeFormatter SHORT_DATETIME_FORMATTER = DateTimeFormatter.ofPattern("yyMMddHHmmss");
public static final DateTimeFormatter DATETIME_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
public static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd");

  /**
     * 返回当前日期时间
     * @return
     */
    public static LocalDateTime getCurrentLocalDateTime() {
        return LocalDateTime.now();
    }

 /**
     * yyyyMMddHHmmss
     * @return
     */
    public static String getCurrentDateTimeStr() {
        return LocalDateTime.now().format(DATETIME_FORMATTER);
    }

   /**
     * yyMMddHHmmss
     * @return
     */
    public static String getCurrentShortDateTimeStr() {
        return LocalDateTime.now().format(SHORT_DATETIME_FORMATTER);
    }
     public static LocalDateTime parseLocalDateTime(String dateTimeStr, String pattern) {
        return LocalDateTime.parse(dateTimeStr, DateTimeFormatter.ofPattern(pattern));
    }
     public static String getCurrentDateTimeStr(String pattern) {
        return LocalDateTime.now().format(DateTimeFormatter.ofPattern(pattern));
    }
    public static String formatLocalDateTime(LocalDateTime datetime, String pattern) {
        return datetime.format(DateTimeFormatter.ofPattern(pattern));
    }
     public static LocalDateTime parseLocalDateTime(String dateTimeStr) {
        return LocalDateTime.parse(dateTimeStr, DATETIME_FORMATTER);
    }
     public static String formatLocalDateTime(LocalDateTime datetime) {
        return datetime.format(DATETIME_FORMATTER);
    }
     public static Long toEpochMilli(LocalDateTime dateTime) {
        return dateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
    }

jodaTime

常用方法

#增加时间
DateTime dateTime = new DateTime();
long millis = dateTime.plusDays(1).withTimeAtStartOfDay().getMillis();
#时间解析  
DateTimeFormatter format = DateTimeFormat .forPattern("yyyy-MM-dd HH:mm:ss");  
DateTime dateTime2 = DateTime.parse("2012-12-21 23:22:45", format);    
#时间格式化,输出==> 2012/12/21 23:22:45 Fri    
String string_u = dateTime2.toString("yyyy/MM/dd HH:mm:ss EE");    
System.out.println(string_u);    
#格式化带Locale,输出==> 2012年12月21日 23:22:45 星期五    
String string_c = dateTime2.toString("yyyy年MM月dd日 HH:mm:ss EE",Locale.CHINESE);    
System.out.println(string_c); 
#判断是否闰月    
DateTime dt4 = new DateTime();    
org.joda.time.DateTime.Property month = dt4.monthOfYear();    
System.out.println("是否闰月:" + month.isLeap());  
#当月开始日期
DateTime dateTime = DateTimeFormat.forPattern("yyyy-MM").parseDateTime(yearMonth);
return dateTime.withDayOfMonth(dateTime.dayOfMonth().getMinimumValue()).toString("yyyy-MM-dd");
#当月结束日期
DateTime dateTime = DateTimeFormat.forPattern("yyyy-MM").parseDateTime(yearMonth);
return dateTime.withDayOfMonth(dateTime.dayOfMonth().getMaximumValue()).toString("yyyy-MM-dd");
#某周的开始日期
DateTime recordDate = DateTimeFormat.forPattern("yyyy-MM-dd").parseDateTime(recordDateStr);
return recordDate.plusDays(1 - recordDate.getDayOfWeek()).toString("yyyy-MM-dd");

java.util.date

常用方法

#Date获取时间差
long time1 = c1.getTimeInMillis();
long time2 = c2.getTimeInMillis();
#Calculate difference in milliseconds
long diff = time2 - time1;
#Difference in seconds
long diffSec = diff / 1000;
System.out.println("Difference in seconds "+diffSec);
#Difference in minutes
long diffMin = diff / (60 * 1000);
System.out.println("Difference in minutes "+diffMin);
#Difference in hours
long diffHours = diff / (60 * 60 * 1000);
System.out.println("Difference in hours "+diffHours);
#Difference in days
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.println("Difference in days "+diffDays);
#创建日期对象,把当前的时间
System.out.println(new Date()); // Tue Jan 16 14:37:35 CST 2019
#创建日期对象,把当前的毫秒值转成日期对象
System.out.println(new Date(0L)); // Thu Jan 01 08:00:00 CST 1970

calender

常用方法

#创建Calendar对象
Calendar cal = Calendar.getInstance();
//设置年 
int year = cal.get(Calendar.YEAR);
//设置月
int month = cal.get(Calendar.MONTH) + 1;
//设置日
int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
System.out.print(year + "年" + month + "月" + dayOfMonth + "日");
#使用add方法
cal.add(Calendar.DAY_OF_MONTH, 2); // 加2天
cal.add(Calendar.YEAR, -3); // 减3年
System.out.print(year + "年" + month + "月" + dayOfMonth + "日"); // 2016年11月18日;
#getTime
Calendar cal = Calendar.getInstance();
Date date = cal.getTime();
System.out.println(date); // Tue Jan 16 16:03:09 CST 2019
#获取某个月最后一天
public static String getLastDayOfMonth(int year,int month){
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR , year);
        calendar.set(Calendar.MONTH , month - 1);
        calendar.set(Calendar.DATE , 1);
        calendar.add(Calendar.MONTH, 1);
        calendar.add(Calendar.DAY_OF_YEAR , -1);
        return calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH) + 1) + "-" +
                calendar.get(Calendar.DAY_OF_MONTH);
}
#获取某一年的Calendar 
private static Calendar getCalendarFormYear(int year){
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        cal.set(Calendar.YEAR, year);
        return cal;
}
#获取某一周开始的第一天
public static String getStartDayOfWeekNo(int year,int weekNo){
        Calendar cal = getCalendarFormYear(year);
        cal.set(Calendar.WEEK_OF_YEAR, weekNo);
        return cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1) + "-" +
                cal.get(Calendar.DAY_OF_MONTH);
}
#获取某一周开始的最后一天
public static String getEndDayOfWeekNo(int year,int weekNo){
        Calendar cal = getCalendarFormYear(year);
        cal.set(Calendar.WEEK_OF_YEAR, weekNo);
        cal.add(Calendar.DAY_OF_WEEK, 6);
        return cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1) + "-" +
                cal.get(Calendar.DAY_OF_MONTH);
}
#取得当前日期是多少周
public static int getWeekOfYear(Date date) {
        Calendar c = new GregorianCalendar();
        c.setFirstDayOfWeek(Calendar.MONDAY);
        c.setMinimalDaysInFirstWeek(7);
        c.setTime(date);
        return c.get(Calendar.WEEK_OF_YEAR);
}
#得到某年某周的第一天
public static Date getFirstDayOfWeek(int year, int week) {
        Calendar c = new GregorianCalendar();
        c.set(Calendar.YEAR, year);
        c.set(Calendar.MONTH, Calendar.JANUARY);
        c.set(Calendar.DATE, 1);
        Calendar cal = (GregorianCalendar) c.clone();
        cal.add(Calendar.DATE, week * 7);
        return getFirstDayOfWeek(cal.getTime());
}
#取得当前日期所在周的第一天  
public static Date getFirstDayOfWeek(Date date) {
        Calendar c = new GregorianCalendar();
        c.setFirstDayOfWeek(Calendar.MONDAY);
        c.setTime(date);
        c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek()); // Monday
        return c.getTime();
}

hutool

三方工具类,很方便

常用方法

#根据str获取时间戳
DateUtil.parse(str).getTime()
#时间戳转str
Date sellStartTime = DateUtil.date(long);
DateUtil.formatDateTime(sellStartTime)
上一篇:1.29号Java复习题目(针对面试示例版尝试(未分类))


下一篇:关于yyyy-MM-dd格式日期字符串,解析成LocalDateTime遇到的问题