使用Calendar獲取時間區間
用來用去還是這個簡單

Calendar

其實我更想用Hutool的時間工具包,然而沒辦法的情況下只好用原生的

  • 取昨天0點到今天0點,比如一天結束了要統計結果產生某報表的時候
Calendar cal = Calendar.getInstance();
cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
Date end = cal.getTime(); //今天0點
cal.add(Calendar.DATE, -1);
Date start = cal.getTime(); // 昨天0點
  • 取當下時間回推5分鐘,比如我有一個服務每5分鐘要匯報一次
    • 要注意的是calendar一般不會用到毫秒,然而取成時間戳的時候還是會露出尾巴來
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.SECOND, 0); // 當下這分鐘
calendar.set(Calendar.MILLISECOND, 0);
Date end = calendar.getTime();
calendar.add(Calendar.MINUTE, -5);
Date start = calendar.getTime();

近期其他心得

  • ObjectList透過stream轉換成Map(例如我想得出一個用Id可以快速獲取Name的Map),當Key重複的時候,他不會自動把舊的頂掉,而是會拋出異常
  • 所以需要加上第3個參數,說明要保留誰,例如(oldValue, newValue) -> newValue)就是留下新的
Map<Integer, String> map = list.stream().collect(Collectors.toMap(Person::getId, Person::getName,(oldValue, newValue) -> newValue));

上次修改於 2022-06-10