zoukankan      html  css  js  c++  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;
      }

    知识在于积累!

    千里之行始于足下!

  • 相关阅读:
    1053: 正弦函数
    1052: 数列求和4
    1051: 平方根的和
    1050: 阶乘的累加和
    POJ 1321 棋盘问题(搜索的方式)
    HDU 1176 免费馅饼
    BZOJ 2423 (求LCS的长度和种类数)
    HDU 2612 (2次BFS,有点小细节)
    POJ 1088 滑雪(模板题 DFS+记忆化)
    HRBUST 1186 青蛙过河 (思路错了)
  • 原文地址:https://www.cnblogs.com/lori/p/8920003.html
Copyright © 2011-2022 走看看