java日期操作

    public static void main(String[] args) {
        Calendar now = Calendar.getInstance();
        System.out.println("年: " + now.get(Calendar.YEAR));
        System.out.println("月: " + (now.get(Calendar.MONTH) + 1) + "");
        System.out.println("日: " + now.get(Calendar.DAY_OF_MONTH));
        System.out.println("时: " + now.get(Calendar.HOUR_OF_DAY));
        System.out.println("分: " + now.get(Calendar.MINUTE));
        System.out.println("秒: " + now.get(Calendar.SECOND));
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateNowStr = sdf.format(date);
        System.out.println("格式化后的日期:" + dateNowStr);
        String str = "2017-07-24 16:42:15";
        Date date2 = null;
        try {
            date2 = sdf.parse(str);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        System.out.println("字符串转日期:" + date2);
        //根据日期字符串转date对象获取月份
        LocalDate localDate = date2.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        int month = localDate.getMonthValue();
        System.out.println("" + month);
    }

posted @ 2017-07-24 16:52  程序员の奇妙冒险  阅读(12)  评论(0)    收藏  举报  来源