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; }
知识在于积累!
千里之行始于足下!
相关推荐
编程爱好者联盟 2016-10-24
wangpaiyonghu 2020-06-28
心丨悦 2019-12-30
seekerhit 2019-10-25
Java高知 2015-04-24
Holyn 2014-11-21
鸣宇淳 2013-08-14
wujun 2014-03-25
84183557 2019-07-01
牧场SZShepherd 2015-04-11
bluesmore 2014-08-23
langwang 2017-06-19
流量监控lookman 2017-06-18
ihtczte 2012-12-20
凯哥Java 2012-11-02