天天看點

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;
  }      

知識在于積累!

千裡之行始于足下!

作者:倉儲大叔,張占嶺,

榮譽:微軟MVP

QQ:853066980

支付寶掃一掃,為大叔打賞!

java~日期與字元串的轉化