玩转localdatetime

废话不多说,直接上代码

 1 import java.text.SimpleDateFormat;
 2 import java.time.*;
 3 import java.time.temporal.TemporalAdjusters;
 4 import java.util.ArrayList;
 5 import java.util.Calendar;
 6 import java.util.List;
 7 
 8 public class TimeUtil {
 9     //时间戳转LocalDateTime
10     public static LocalDateTime getLocalDateTime(long timestamp) {
11         Instant instant = Instant.ofEpochMilli(timestamp);
12         ZoneId zone = ZoneId.systemDefault();
13         return LocalDateTime.ofInstant(instant, zone);
14     }
15 
16     //获取当月最后一天
17     public static LocalDateTime getLastDayOfCurrentMonth(LocalDateTime localDateTime) {
18         return localDateTime.with(TemporalAdjusters.lastDayOfMonth()).toLocalDate().atStartOfDay();
19     }
20 
21     //获取当月第一天
22     public static LocalDateTime getFirstDayOfCurrentMonth(LocalDateTime localDateTime) {
23         return localDateTime.with(TemporalAdjusters.firstDayOfMonth()).toLocalDate().atStartOfDay();
24     }
25 
26     //获取当日凌晨
27     public static LocalDateTime getMorning(LocalDateTime localDateTime) {
28         return localDateTime.toLocalDate().atStartOfDay();
29     }
30 
31     public static List<String> getMonthBetween(int year) {
32         try {
33             ArrayList<String> result = new ArrayList<>();
34             SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");//格式化为年月
35 
36             Calendar min = Calendar.getInstance();
37             Calendar max = Calendar.getInstance();
38             min.setTime(sdf.parse(year + "-1"));//获取当前年份第一个月
39 
40             max.setTime(sdf.parse(year + "-12"));//获取当前年份最后一月
41 
42             Calendar curr = min;
43             while (curr.before(max)) {
44                 result.add(sdf.format(curr.getTime()));
45                 curr.add(Calendar.MONTH, 1);
46             }
47             return result;
48         } catch (Exception e) {
49             return null;
50         }
51     }
52 }

 

上一篇:JDK1.8新增


下一篇:【redis前传】自己手写一个LRU策略 | redis淘汰策略