java 工具类日期工具类

1.DateTimeHelper.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
package cn.togeek.util;
 
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.lang.Pair;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
 
import cn.togeek.enums.DateType;
 
import java.nio.charset.Charset;
import java.time.DayOfWeek;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.YearMonth;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
 
public class DateTimeHelper {
   public static final String DATE_PATTERN = "yyyy-MM-dd";
   public static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern(DATE_PATTERN);
 
   public static final String DATE_STR_PATTERN = "yyyy年MM月dd日";
 
   public static final DateTimeFormatter DATE_STR_FORMATTER = DateTimeFormatter.ofPattern(DATE_STR_PATTERN);
 
   public static final String DATETIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
   public static final DateTimeFormatter DATETIME_FORMATTER = DateTimeFormatter.ofPattern(DATETIME_PATTERN);
 
   public static final String DATETIME_96_PATTERN = "MMdd HH:mm";
 
   public static final DateTimeFormatter DATETIME_96_FORMATTER = DateTimeFormatter.ofPattern(DATETIME_96_PATTERN);
 
   public static final String TIME_HM_PATTERN = "HH:mm";
 
   public static final DateTimeFormatter DATETIME_96_TIME_FORMATTER = DateTimeFormatter.ofPattern(TIME_HM_PATTERN);
 
   public static final DateTimeFormatter TIME_HM_FORMATTER = DateTimeFormatter.ofPattern(TIME_HM_PATTERN);
 
   public static final String DATE_96_PATTERN = "MMdd ";
 
   public static final DateTimeFormatter DATE_96_FORMATTER = DateTimeFormatter.ofPattern(DATE_96_PATTERN);
 
   public static final String MONTH_DAY_PATTERN = "MM月dd日 ";
 
   public static final DateTimeFormatter MONTH_DAY_FORMATTER = DateTimeFormatter.ofPattern(MONTH_DAY_PATTERN);
 
   public static final String END_TIME_STR = "24:00";
 
   private static final Map<String, DateTimeFormatter> formatters = new HashMap<>();
 
   static {
      formatters.put(DATE_PATTERN, DATE_FORMATTER);
      formatters.put(DATETIME_PATTERN, DATETIME_FORMATTER);
   }
 
   private DateTimeHelper() {
   }
 
   public static LocalDate date2LocalDate(Date date) {
      Instant instant = date.toInstant();
      ZoneId zoneId = ZoneId.systemDefault();
      return instant.atZone(zoneId).toLocalDate();
   }
 
   public static LocalDateTime date2LocalDateTime(Date date) {
      Instant instant = date.toInstant();
      ZoneId zoneId = ZoneId.systemDefault();
      return instant.atZone(zoneId).toLocalDateTime();
   }
 
   public static LocalDateTime text2LocalDateTime(String timeText) {
      return text2LocalDateTime(timeText, null);
   }
 
   public static LocalDateTime text2LocalDateTime(String timeText, String pattern) {
      pattern = pattern == null ? DATETIME_PATTERN : pattern;
      if(formatters.get(pattern) == null) {
         formatters.put(pattern, DateTimeFormatter.ofPattern(pattern));
      }
 
      return LocalDateTime.parse(timeText, formatters.get(pattern));
   }
 
   public static String localDateTime2Text(LocalDateTime dateTime) {
      return localDateTime2Text(dateTime, null);
   }
 
   public static String localDateTime2Text(LocalDateTime dateTime, String pattern) {
      pattern = pattern == null ? DATETIME_PATTERN : pattern;
      if(formatters.get(pattern) == null) {
         formatters.put(pattern, DateTimeFormatter.ofPattern(pattern));
      }
 
      return formatters.get(pattern).format(dateTime);
   }
 
   public static LocalDate text2LocalDate(String dateText) {
      return text2LocalDate(dateText, null);
   }
 
   public static LocalDate text2LocalDate(String timeText, String pattern) {
      pattern = pattern == null ? DATE_PATTERN : pattern;
      if(formatters.get(pattern) == null) {
         formatters.put(pattern, DateTimeFormatter.ofPattern(pattern));
      }
 
      return LocalDate.parse(timeText, formatters.get(pattern));
   }
 
   public static String localDate2Text(LocalDate date) {
      return localDate2Text(date, null);
   }
 
   public static String localDate2Text(LocalDate date, String pattern) {
      pattern = pattern == null ? DATE_PATTERN : pattern;
      if(formatters.get(pattern) == null) {
         formatters.put(pattern, DateTimeFormatter.ofPattern(pattern));
      }
 
      return formatters.get(pattern).format(date);
   }
 
   public static Date localDate2Date(LocalDate localDate) {
      ZoneId zone = ZoneId.systemDefault();
      ZonedDateTime zonedDateTime = localDate.atStartOfDay(zone);
      return Date.from(zonedDateTime.toInstant());
   }
 
   public static Date localDateTime2Date(LocalDateTime localDateTime) {
      ZoneId zone = ZoneId.systemDefault();
      Instant instant = localDateTime.atZone(zone).toInstant();
      return Date.from(instant);
   }
 
   public static long localDateTime2Timestamp(LocalDateTime localDateTime) {
      ZoneId zone = ZoneId.systemDefault();
      Instant instant = localDateTime.atZone(zone).toInstant();
      return instant.toEpochMilli();
   }
 
   public static LocalDateTime timestamp2LocalDateTime(long timestamp) {
      Instant instant = Instant.ofEpochMilli(timestamp);
      ZoneId zone = ZoneId.systemDefault();
      return LocalDateTime.ofInstant(instant, zone);
   }
 
   public static LocalDateTime beginOfDay(LocalDateTime localDateTime) {
      return localDateTime.with(LocalTime.MIN);
   }
 
   public static LocalDateTime beginOfDay(LocalDate localDate) {
      return LocalDateTime.of(localDate, LocalTime.MIN);
   }
 
   public static LocalDateTime endOfDay(LocalDateTime localDateTime) {
      return localDateTime.with(LocalTime.MAX);
   }
 
   public static LocalDateTime endOfDay(LocalDate localDate) {
      return LocalDateTime.of(localDate, LocalTime.MAX);
   }
 
   public static LocalDateTime beginOfMonth(LocalDateTime localDateTime) {
      return localDateTime.with(TemporalAdjusters.firstDayOfMonth()).with(LocalDateTime.MIN);
   }
 
   public static LocalDateTime beginOfMonth(LocalDate localDate) {
      return LocalDateTime.of(localDate.with(TemporalAdjusters.firstDayOfMonth()), LocalTime.MIN);
   }
 
   public static LocalDateTime endOfMonth(LocalDateTime localDateTime) {
      return localDateTime.with(TemporalAdjusters.lastDayOfMonth()).with(LocalDateTime.MAX);
   }
 
   public static LocalDateTime endOfMonth(LocalDate localDate) {
      return LocalDateTime.of(localDate.with(TemporalAdjusters.lastDayOfMonth()), LocalTime.MAX);
   }
 
   public static LocalDateTime beginOfYear(LocalDateTime localDateTime) {
      return localDateTime.with(TemporalAdjusters.firstDayOfYear()).with(LocalDateTime.MIN);
   }
 
   public static LocalDateTime beginOfYear(LocalDate localDate) {
      return LocalDateTime.of(localDate.with(TemporalAdjusters.firstDayOfYear()), LocalTime.MIN);
   }
 
   public static LocalDateTime endOfYear(LocalDateTime localDateTime) {
      return localDateTime.with(TemporalAdjusters.lastDayOfYear()).with(LocalDateTime.MAX);
   }
 
   public static LocalDateTime endOfYear(LocalDate localDate) {
      return LocalDateTime.of(localDate.with(TemporalAdjusters.lastDayOfYear()), LocalTime.MAX);
   }
 
   public static LocalDate firstDayOfMonth(LocalDate localDate) {
      return localDate.with(TemporalAdjusters.firstDayOfMonth());
   }
 
   public static LocalDate lastDayOfMonth(LocalDate localDate) {
      return localDate.with(TemporalAdjusters.lastDayOfMonth());
   }
 
   public static LocalDate firstDayOfYear(LocalDate localDate) {
      return localDate.with(TemporalAdjusters.firstDayOfYear());
   }
 
   public static LocalDate lastDayOfYear(LocalDate localDate) {
      return localDate.with(TemporalAdjusters.lastDayOfYear());
   }
 
 
   public static List<LocalDate> getDateList(LocalDate beginDate, LocalDate endDate) {
      long range = ChronoUnit.DAYS.between(beginDate, endDate) + 1;
      List<LocalDate> list = new ArrayList<>();
      for (long i = 0; i < range; i++) {
         list.add(beginDate.plusDays(i));
      }
 
      return list;
   }
 
   /**
    * 根据年月字符串获取当月第一天和最后一天
    */
   public static Map<String, LocalDate> getDateByYmstr(String date) {
      String str = date + "-01";
      LocalDate firstDay = LocalDate.parse(str, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
      LocalDate lastDate = firstDay.with(TemporalAdjusters.lastDayOfMonth());
      Map<String, LocalDate> map = new HashMap<>();
      map.put("firstDay", firstDay);
      map.put("lastDate", lastDate);
      return map;
   }
 
   /**
    * 获取前一天日期
    */
   public static String yesterday() {
      // 获取当前日期
      LocalDate today = LocalDate.now();
      // 获取当前日期的前一天
      return today.minusDays(1).toString();
   }
 
   /**
    * 获取后一天日期
    */
   public static String tomorrow() {
      // 获取当前日期
      LocalDate today = LocalDate.now();
      // 获取当前日期的前一天
      return today.plusDays(1).toString();
   }
 
   public static LocalDateTime strToDateTime(String dateStr, String timeStr) {
      return LocalDateTime.of(LocalDate.parse(dateStr), LocalTime.parse(timeStr));
   }
 
   public static String numberToTimeStr(int i) {
      return String.format("%02d:%02d", i * 15 / 60, i * 15 % 60);
   }
 
 
   public static int timeStrToNumber(String timeStr) {
      String[] split = timeStr.split(":");
      return NumberUtil.toBigInteger(split[0]).intValue() * 4 + NumberUtil.toBigInteger(split[1]).intValue() / 15;
   }
 
   public static LocalTime numberToLocalTime(int i) {
      try {
         return LocalTime.of(i*15/60, i*15%60);
      } catch(Exception e){
         return LocalTime.MIN;
      }
 
   }
 
   public static synchronized String fixTime(String timeStr, boolean hasSecond) {
      if (!timeStr.contains(":")) {
         throw new IllegalArgumentException("时间格式有误");
      }
      if (timeStr.contains(" ")) {
         timeStr = timeStr.split(" ")[1];
      }
      List<String> split = Arrays.stream(timeStr.split(":")).collect(Collectors.toList());
      if (!hasSecond && split.size() == 3) {
         split.remove(2);
      }
      StringBuffer time = new StringBuffer();
      for (int i = 0; i < split.size(); i++) {
         String str = split.get(i);
         String it;
         if(str.length() < 2) {
            it = "0" + str;
         }
         else {
            it = str;
         }
         time.append(it);
         if(i != split.size() - 1) {
            time.append(":");
         }
      }
      return time.toString();
   }
 
   public static String fixDate(String bsStr) {
      String[] fixed;
      String sepPoint = ".";
      boolean point = bsStr.contains(sepPoint);
      if (point) {
         fixed = bsStr.split("\\.");
      }
      else {
         fixed = bsStr.split("-");
      }
      String sep = point ? sepPoint : "-";
      return String.format("%s%s%02d%s%02d", fixed[0], sep, Integer.parseInt(fixed[1]), sep,
         Integer.parseInt(fixed[2]));
   }
 
   public static List<String> genarateTime(boolean has2400) {
      if (has2400) {
         return IntStream.rangeClosed(1, 96).mapToObj(i -> numberToTimeStr(i)).collect(Collectors.toList());
      }
      else {
         return IntStream.rangeClosed(0, 95).mapToObj(i -> numberToTimeStr(i)).collect(Collectors.toList());
      }
   }
 
   /***
    * 00:15-24:00
    * @param start
    * @param end
    * @param format
    * @return
    * @param <T>
    */
   public static <T> List<T> getDateList96(LocalDate start, LocalDate end, Function<LocalDateTime, T> format) {
      List<T> list = Lists.newArrayList();
 
      LocalDate item = start;
      while (item.isBefore(end) || item.isEqual(end)) {
         LocalTime time = LocalTime.MIN;
         for (int i = 0; i < 96; i++) {
            time = time.plusMinutes(15l);
            list.add(format.apply(LocalDateTime.of(item, time)));
         }
 
         item = item.plusDays(1l);
      }
 
      return list;
   }
 
   public static void main(String[] args) {
      List<LocalDateTime> dateList96 = DateTimeHelper.getDateList96(LocalDate.now(), LocalDate.now(), Function.identity());
      System.out.println(dateList96);
   }
 
   public static List<String> getDateList96(LocalDate start, LocalDate end) {
      return getDateList96(start, end, DEFAULT_DATE_96_FUNC);
   }
 
   public static final Function<LocalDateTime, String> DEFAULT_DATE_96_FUNC =
      e -> e.toLocalTime().equals(LocalTime.MIN) ? DATE_96_FORMATTER.format(e).concat(END_TIME_STR) :
         DATETIME_96_FORMATTER.format(e);
 
   public static List<String> getDateList96Time(LocalDate start, LocalDate end) {
      List<String> dateList96Time = getDateList96(start, end, DEFAULT_DATE_FUNC);
      return dateList96Time.stream().map(l -> {
         if ("00:00".equals(l)) {
            l = "24:00";
         }
         return l;
      }).collect(Collectors.toList());
   }
 
   public static final Function<LocalDateTime, String> DEFAULT_DATE_FUNC =
           e -> DATETIME_96_TIME_FORMATTER.format(e);
 
   public static List<String> getBetweenToTime(String startTime, String endTime) {
      int start = timeStrToNumber(startTime);
      int end = timeStrToNumber(endTime);
      return IntStream.range(start, end + 1).mapToObj(DateTimeHelper::numberToTimeStr).collect(Collectors.toList());
   }
 
   public static LocalDate parseLocalDate(Object date) {
      String[] parttens = {
         "yyyy-MM-dd",
         "yyyy-M-dd",
         "yyyy-M-d",
         "yyyy.MM.dd",
         "yyyy.M.dd",
         "yyyy.M.d",
         "yyyy年MM月dd日",
         "yyyy年M月dd日",
         "yyyy年M月d日",
         "yyyy/MM/dd",
         "yyyy/M/dd",
         "yyyy/M/d",
         "yyyyMMdd",
         "yyyyMdd",
         "yyyyMd",
      };
      if(date == null) {
         return null;
      }
      if(date instanceof Date) {
         return LocalDateTimeUtil.of(((Date) date)).toLocalDate();
      } else if (date instanceof String) {
         String dateStr = (String) date;
         for(String partten : parttens) {
            try {
               return LocalDate.parse(dateStr, DateTimeFormatter.ofPattern(partten));
            }
            catch(Exception e) { }
         }
      }
      return null;
   }
 
   public static boolean isBetween(LocalDate start, LocalDate end, LocalDate...  dates) {
      boolean ok = true;
      for(LocalDate date : dates) {
         ok &= !date.isBefore(start) && !date.isAfter(end);
      }
      return ok;
   }
 
   public static List<String> getPoint96(){
      return IntStream.rangeClosed(1, 96).mapToObj(DateTimeHelper::numberToTimeStr).collect(Collectors.toList());
   }
 
   /**
    *  获取指定开始结束日期内的日期类型
    * @param begin
    * @param end
    * @return
    */
   public static Map<DateType,List<LocalDate>> getSortedDays(LocalDate begin, LocalDate end){
      Map<DateType,List<LocalDate>> dateTypeListMap = new LinkedHashMap<>();
      List<LocalDate> visited = new ArrayList<>();
      IntStream.rangeClosed(begin.getYear(), end.getYear()).forEach(year->{
         String url = "http://timor.tech/api/holiday/year/"+year;
         String result = HttpUtil.get(url, Charset.forName("UTF-8"));
         JSONObject info = JSONObject.parseObject(result);
         JSONObject holiday = info.getJSONObject("holiday");
         for(String dateStr : holiday.keySet()) {
            String fullDate = year+"-"+dateStr;
            JSONObject dateInfo = holiday.getJSONObject(dateStr);
            Boolean isHoliday = dateInfo.getBoolean("holiday");
            DateType dateType = isHoliday ? DateType.HOLIDAY : DateType.ADJUSTHOLIDAY;
            dateTypeListMap.computeIfAbsent(dateType,(s)-> new ArrayList<>());
            LocalDate date = LocalDate.parse(fullDate);
            visited.add(date);
            dateTypeListMap.get(dateType).add(date);
         }
      });
      while(!begin.isAfter(end)) {
         if(!visited.contains(begin)) {
            DayOfWeek dayOfWeek = begin.getDayOfWeek();
            DateType dateType;
            switch(dayOfWeek) {
               case SATURDAY:
                  dateType = DateType.SATURDAY;
                  break ;
               case SUNDAY:
                  dateType = DateType.SUNDAY;
                  break ;
               default:
                  dateType = DateType.WORKINGDAY;
                  break;
            }
            dateTypeListMap.computeIfAbsent(dateType,(s)-> new ArrayList<>());
            dateTypeListMap.get(dateType).add(begin);
         }
         begin = begin.plusDays(1);
      }
 
      return dateTypeListMap;
   }
 
   /**
    *  获取指定开始结束日期内的日期类型
    * @param begin
    * @param end
    * @return
    */
   public static Map<LocalDate,DateType> getDaysType(LocalDate begin, LocalDate end){
      Map<LocalDate,DateType> dateTypeListMap = new LinkedHashMap<>();
      IntStream.rangeClosed(begin.getYear(), end.getYear()).forEach(year->{
         String url = "http://timor.tech/api/holiday/year/"+year;
         String result = HttpUtil.get(url, Charset.forName("UTF-8"));
         JSONObject info = JSONObject.parseObject(result);
         JSONObject holiday = info.getJSONObject("holiday");
         for(String dateStr : holiday.keySet()) {
            String fullDate = year+"-"+dateStr;
            LocalDate date = LocalDate.parse(fullDate);
            if(DateTimeHelper.isBetween(begin,end,date)) {
               JSONObject dateInfo = holiday.getJSONObject(dateStr);
               Boolean isHoliday = dateInfo.getBoolean("holiday");
               DateType dateType = isHoliday ? DateType.HOLIDAY : DateType.ADJUSTHOLIDAY;
               dateTypeListMap.put(date,dateType);
            }
         }
      });
      LocalDate cur = LocalDate.from(begin);
      while(!cur.isAfter(end)) {
         if(!dateTypeListMap.keySet().contains(cur)) {
            DayOfWeek dayOfWeek = cur.getDayOfWeek();
            DateType dateType;
            switch(dayOfWeek) {
               case SATURDAY:
                  dateType = DateType.SATURDAY;
                  break ;
               case SUNDAY:
                  dateType = DateType.SUNDAY;
                  break ;
               default:
                  dateType = DateType.WORKINGDAY;
                  break;
            }
            dateTypeListMap.put(cur,dateType);
         }
         cur = cur.plusDays(1);
      }
      return dateTypeListMap;
   }
 
 
   /**
    * 给定开始结束日期,给定一个月份,求这个月在给定开始结束时间内的开始结束时间
    * @param begin
    * @param end
    * @param month
    * @return
    */
   public static Pair<LocalDate,LocalDate> getBeginAndEnd(LocalDate begin, LocalDate end, int month){
      LocalDate cur = LocalDate.from(begin);
      LocalDate start = null,ends = null;
      while(!cur.isAfter(end)) {
         if(cur.getMonthValue() < month) {
            cur = cur.plusMonths(1);
            continue;
         }
         if(cur.getMonthValue() > month) {
            break;
         }
         if(start == null) {
            start = cur;
         }
         cur = cur.plusDays(1);
      }
      ends = cur;
      return Pair.of(start,ends.getMonthValue() == month?ends:ends.minusDays(1));
   }
 
   /**
    * 根据月份获取该月每周的日期列表
    * @param yearMonth
    * @return
    */
   public static Map<Integer,List<LocalDate>> getWeekMap(YearMonth yearMonth){
      YearMonth month = YearMonth.from(yearMonth);
      LocalDate start = LocalDate.of(month.getYear(),month.getMonth(),1);
      int dayOfMonth = month.lengthOfMonth();
      LocalDate end = LocalDate.of(month.getYear(),month.getMonth(), dayOfMonth);
      Map<Integer,List<LocalDate>> map = new LinkedHashMap<>();
      int week = 1;
      boolean willPlus = false;
      while(!start.isAfter(end)) {
         List<LocalDate> dateList = map.computeIfAbsent(week, (w)->Lists.newArrayList());
         dateList.add(start);
         if(willPlus) {
            willPlus = false;
            week++;
         }
         start = start.plusDays(1);
         if(start.getDayOfWeek().getValue() == 7) {
            willPlus = true;
         }
      }
      return map;
   }
    
}

  

2.DateType.java

复制代码
package cn.togeek.enums;

/**
 * 日期类型:周六,周日,工作日,法定节假日,调休节假日
 */
public enum DateType {
   SATURDAY("周六"),
   SUNDAY("周日"),
   WORKINGDAY("工作日"),
   HOLIDAY("节假日"),
   ADJUSTHOLIDAY("调休节假日");

   DateType(String typeName) {
      this.typeName = typeName;
   }

   private String typeName;

   public String getTypeName() {
      return typeName;
   }

   public static DateType getDataTypeByName(String typeName) {
      for(DateType dateType : DateType.values()) {
         if(dateType.getTypeName().equals(typeName)) {
            return dateType;
         }
      }
      return null;
   }
public static Map<Integer,List<LocalDate>> getWeekMap(YearMonth yearMonth){
    YearMonth month = YearMonth.from(yearMonth);
LocalDate start = LocalDate.of(month.getYear(),month.getMonth(),1);
int dayOfMonth = month.lengthOfMonth();
LocalDate end = LocalDate.of(month.getYear(),month.getMonth(), dayOfMonth);
Map<Integer,List<LocalDate>> map = new LinkedHashMap<>();
int week = 1;
boolean willPlus = false;
while(!start.isAfter(end)) {
List<LocalDate> dateList = map.computeIfAbsent(week, (w)->Lists.newArrayList());
dateList.add(start);
if(willPlus) {
willPlus = false;
week++;
}
start = start.plusDays(1);
if(start.getDayOfWeek().getValue() == 7) {
willPlus = true;
}
}
return map;
}
}
复制代码

 3.BeanUtils.java

复制代码
package cn.togeek.util;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Pair;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import io.swagger.annotations.ApiModelProperty;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;

@Slf4j
public class BeanUtils {

   private static final Logger logger = LoggerFactory.getLogger(BeanUtils.class);

   /**
    * map 对象转对象
    * @param origion
    * @param t
    * @param <T>
    */
   public static<T> void mapToBean(Map<String,Object> origion,T t){
      Class<?> aClass = t.getClass();
      Map<String, Field> mapping = new LinkedHashMap<>();
      while(aClass != Object.class) {
         Map<String, Field> cur = Arrays.stream(aClass.getDeclaredFields())
            .map(field -> Pair.of(field.getName().replaceAll("_", "").toLowerCase(), field))
            .collect(Collectors.toMap(o -> o.getKey(), o -> o.getValue()));
         mapping.putAll(cur);
         aClass = aClass.getSuperclass();
      }
      for(Map.Entry<String, Object> entry : origion.entrySet()) {
         String field = entry.getKey();
         Object value = entry.getValue();
         if(ReflectUtil.hasField(aClass, field) &&
            ReflectUtil.getField(aClass,field).getType().equals(value.getClass())) {
            ReflectUtil.setFieldValue(t,field, value);
         } else {
            String field2 = field.replaceAll("_", "").toLowerCase();
            if(mapping.containsKey(field2) && mapping.get(field2).getType().equals(value.getClass())) {
               ReflectUtil.setFieldValue(t,mapping.get(field2), value);
               continue;
            }
            logger.warn("origion map key:{} not in Class:{}",field,aClass);
         }
      }
   }

   /**
    * 获取指定类的注解信息与字段映射关系
    * @param clazz
    * @return
    */
   public static Map<String,Field> getApiModleInfoMap(Class clazz) {
      return Arrays.stream(ReflectUtil.getFields(clazz))
         .filter(f->f.isAnnotationPresent(ApiModelProperty.class)).collect(Collectors.toMap(f->{
            ApiModelProperty annotation = f.getAnnotation(ApiModelProperty.class);
            return annotation.value();
         },f->f,(o1,o2)->o2));
   }

   /**
    * 文件导入时使用
    * @param clazz
    * @param errorInfo
    * @return
    */
   public static <T> List<T> getBeanListFromListMap(Class<T> clazz, MultipartFile file, List<String> errorInfo) throws Exception {
      ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
      List<Map<String,Object>> xlsDataList = reader.readAll();
      Map<String, Field> infoMap = getApiModleInfoMap(clazz);
      ArrayList<T> list = new ArrayList<>();
      xlsDataList.forEach(map -> {
         try {
            T bean = clazz.newInstance();
            list.add(bean);
            map.forEach((key,value) -> {
               Field field = infoMap.get(key);
               if(Objects.isNull(field)) {
                  log.warn(String.format("key:%s not match any class field,it will be ignored,please check!!!",key));
               } else {
                  Class<?> type = field.getType();
                  if(Objects.isNull(value) || value.getClass() == type) {
                     ReflectUtil.setFieldValue(bean,field,value);
                  } else {
                     Object convert = Convert.convert(type, value);
                     ReflectUtil.setFieldValue(bean,field,convert);
                  }
               }
            });
         }
         catch(Exception e) {
            errorInfo.add(e.getMessage());
            e.printStackTrace();
         }
      });
      return list;
   }

}
复制代码

 4.多个list合并成一个list

复制代码
package cn.togeek.util;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.ReflectUtil;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import lombok.AllArgsConstructor;
import lombok.Data;

import cn.togeek.exception.ClientError;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class DateTimeValueUtilPlus {
   public static final String QUART = "QUART";
   public static final String HOUR = "HOUR";
//   public static final String DAY = "DAY";

   public static  <T> List<T> genarate(LocalDate start, LocalDate end, String unit, Builder builder,Class<T> targetClazz){
      List<T> result = new ArrayList<>();
      for(LocalDate s= LocalDate.from(start);!s.isAfter(end);s=s.plusDays(1)) {
         switch(unit) {
            case QUART:
            case HOUR:
               int i = 0;
               for(LocalTime b=LocalTime.MIN;unit.equals(QUART)?i<96:i<24;b=b.plusMinutes(unit.equals(QUART)?15:60)) {
                  T t = ReflectUtil.newInstanceIfPossible(targetClazz);
                  ReflectUtil.setFieldValue(t,builder.dateField,s);
                  ReflectUtil.setFieldValue(t,builder.timeField,b);
                  for(Object[] datum : builder.data) {
                     Class curClass = (Class) datum[0];
                     List<Part> parts = (List<Part>) datum[1];
                     Map<LocalDate,Map<LocalTime,Object>> curOrigionDataMap = (Map<LocalDate,Map<LocalTime,Object>>)datum[2];
                     for(Part part : parts) {
                        String targetField = part.getTargetFieldName();
                        Function function  = part.getOperation();
                        if(ReflectUtil.hasField(targetClazz,targetField)) {
                           Object orDefault = curOrigionDataMap.getOrDefault(s, Maps.newHashMap())
                              .getOrDefault(b, ReflectUtil.newInstanceIfPossible(curClass));
                           Object o = function.apply(orDefault);
                           ReflectUtil.setFieldValue(t,targetField,o);
                        }
                     }
                  }
                  i++;
                  result.add(t);
               }
               break;
            default:
               throw new ClientError("非法参数");
         }
      }


      return result;
   }

   public static class Builder{

      List<Object[]> data = new ArrayList<>();
      int index;
      String dateField;
      String timeField;

      /**
       *
       * @param dateField 目标类 日期字段名
       * @param timeField 目标类 时刻字段名
       * order = 0
       * @return
       */
      public static Builder of(String dateField, String timeField){
         Builder builder = new Builder();
         builder.dateField = dateField;
         builder.timeField = timeField;
         return builder;
      }

      /**
       *
       * @param origionListType 原始类class
       * order = 1
       * @return
       */
      public Builder origionClass(Class origionListType) {
         Object[] element = new Object[4];
         element[0] = origionListType;
         data.add(index, element);
         return this;
      }

      /**
       *
       * @param parts 目标类字段名
       * order = 2
       * @return
       */
      public Builder with(List<Part> parts) {
         data.get(index)[1] = parts;
         return this;
      }

      /**
       * order = 3
       * @param originDateTimeInstanceMap 原始list 按日期时刻分类后的class
       * @return
       */
      public Builder use(Map<LocalDate,Map<LocalTime,Object>> originDateTimeInstanceMap) {
         data.get(index)[2] = originDateTimeInstanceMap;
         return this;
      }

   }

   @Data
   @AllArgsConstructor
   public static class Part{

      //目标类字段名
      private String targetFieldName;

      //function 找到原始instance 后的取值逻辑
      private Function operation;

   }

   public static void main(String[] args) {
      LocalDate start = LocalDate.parse("2023-08-01");
      LocalDate end = LocalDate.parse("2023-08-04");
      List<Power> powerList = DateTimeHelper.getDateList(start, end)
         .stream()
         .map(x -> DateTimeHelper.genarateTime(false).stream().map(t -> {
            Power power = new Power();
            power.setPowerLong(RandomUtil.randomBigDecimal());
            power.setPowerSpot(RandomUtil.randomBigDecimal());
            power.setTime(LocalTime.parse(t));
            power.setInfoDate(x);
            return power;
         }).collect(Collectors.toList()))
         .flatMap(Collection::stream)
         .collect(Collectors.toList());
      List<Price> priceList = DateTimeHelper.getDateList(LocalDate.parse("2023-08-03"), end)
         .stream()
         .map(x -> DateTimeHelper.genarateTime(false).stream().map(t -> {
            Price power = new Price();
            power.setPrice(RandomUtil.randomBigDecimal());
            power.setTime(LocalTime.parse(t));
            power.setBusinessDate(x);
            return power;
         }).collect(Collectors.toList()))
         .flatMap(Collection::stream)
         .collect(Collectors.toList());
      Map<LocalDate,Map<LocalTime,Object>> collectPrice =  priceList.stream()
         .collect(Collectors.groupingBy(Price::getBusinessDate, Collectors.toMap(Price::getTime, Function.identity())));
      Map<LocalDate,Map<LocalTime,Object>> collectPower =  powerList.stream()
         .collect(Collectors.groupingBy(Power::getInfoDate, Collectors.toMap(Power::getTime, Function.identity())));
      List<PricePower> genarate = DateTimeValueUtilPlus.genarate(start, end, DateTimeValueUtilPlus.QUART,
         Builder.of("infoDate", "time")
            .origionClass(Price.class)
            .with(Arrays.asList(new Part("price",(p) -> ((Price) p).price )))
            .use(collectPrice)
            .origionClass(Power.class)
            .with(Arrays.asList(
               new Part("powerSpot",(p) -> ((Power) p).powerSpot),
               new Part("powerLong",(p) -> ((Power) p).powerLong)
            ))
            .use(collectPower),
         PricePower.class);
      System.out.println(JSON.toJSONString(genarate));
   }

   @Data
   static class Power{
      LocalDate infoDate;
      LocalTime time;
      BigDecimal powerSpot;
      BigDecimal powerLong;
   }

   @Data
   static class Price{
      LocalDate businessDate;
      LocalTime time;
      BigDecimal price;
   }

   @Data
   static class PricePower{
      LocalDate infoDate;
      LocalTime time;
      BigDecimal price;
      BigDecimal powerSpot;
      BigDecimal powerLong;
   }

}
复制代码

 

posted @   漂渡  阅读(730)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
历史上的今天:
2021-05-05 数据结构与算法之hash,bitmap简单实现
点击右上角即可分享
微信分享提示