• 参考文章

    public static void main(String[] args) {
    //时间转字符串
    Date currentTime=new Date();
    DateFormat formatter=new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss"); //模板可以多样
    String dateString=formatter.format(currentTime);
    System.out.println(dateString); //2018-12-01 15:47:10
    
    //字符串转时间
    dateString="2018-12-1";
    DateFormat formatter2=new SimpleDateFormat("yyyy-MM-dd");
    Date currentTime2=null;
    try {
        //精确到日的时间字符串转为精确到秒的时间,报错
        //currentTime=formatter.parse(dateString);
        currentTime2=formatter2.parse(dateString);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    //精确到日的时间字符串转为相同精度的时间再转回相同精度的时间
    dateString=formatter2.format(currentTime2);
    System.out.println(dateString); //2018-12-01
    //精确到日的时间字符串转为相同精度的时间再转回精确到秒的时间
    dateString=formatter.format(currentTime2);
    System.out.println(dateString);//2018年12月01日 00:00:00
    

    }

  • 文章里还有获取一个月中的最后一天、单独得到现在的小时、得到两个日期间的间隔天数、把日期前移或后推多少分钟等等方法
  • 代码实例:SpringbootIntegrateMybatis/test/java/DateFormatTest