1. 程式人生 > >java~日期與字串的轉化

java~日期與字串的轉化

在Java裡我們可以通過SimpleDateFormat實現日期型別的格式化,即將它轉為指定格式的字串,當然像YearMonth這種特殊的型別,實現字串轉化最為容易,即直接toString()即可,下面看一下程式碼,兩種格式的轉換。

一 Date到字串轉換

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
sdf.parse(maxDate))//2018-01

二 YearMonth到字串轉換

val from =YearMonth.of(2018,1).toString(); //結果2018-01

三 實現-列舉兩個日期之間的所有月份

 /**
   * from ~ to total months.
   *
   * @param minDate
   * @param maxDate
   * @return
   */
  private static List<String> getMonthBetween(String minDate, String maxDate) {
    ArrayList<String> result = new ArrayList<>();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");//
格式化為年月 Calendar min = Calendar.getInstance(); Calendar max = Calendar.getInstance(); try { min.setTime(sdf.parse(minDate)); min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1); max.setTime(sdf.parse(maxDate)); max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH),
2); } catch (Exception ex) { System.out.println(ex.getMessage()); } Calendar curr = min; while (curr.before(max)) { result.add(sdf.format(curr.getTime())); curr.add(Calendar.MONTH, 1); } return result; }

知識在於積累!

千里之行始於足下!