首页 > 编程 > Java > 正文

Java获取时间年、月、日的方法

2019-11-26 15:10:40
字体:
来源:转载
供稿:网友

本文实例讲述了Java获取时间年、月、日的方法。分享给大家供大家参考。具体实现方法如下:

package com.date.demo; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class DateDemo {   public static void main(String args[]) {     System.out.println("---------------获取当前时间的年月日-----------------");     getMonthDay();     System.out.println("---------------获取自定义时间的年月日-----------------");     getMonthDay2Set();   }   /**    * 获取自定义时间的年月日    */   private static void getMonthDay2Set() {     String dateStr = "2013-11-10 18:45:39";     SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");     Calendar cal = Calendar.getInstance();     Date dt = null;     try {       dt = sdf.parse(dateStr);       cal.setTime(dt);     } catch (ParseException e) {       // TODO Auto-generated catch block       e.printStackTrace();     }     int year = cal.get(Calendar.YEAR);     int month = cal.get(Calendar.MONTH) + 1;     int day = cal.get(Calendar.DAY_OF_MONTH);     int hour = cal.get(Calendar.HOUR_OF_DAY);     int minute = cal.get(Calendar.MINUTE);     int second = cal.get(Calendar.SECOND);     System.out.println("===年===" + year);     System.out.println("===月===" + month);     System.out.println("===日===" + day);     System.out.println("===时===" + hour);     System.out.println("===分===" + minute);     System.out.println("===秒===" + second);   }   /**    * 获取当前时间的年月日    */   private static void getMonthDay() {     Calendar cal = Calendar.getInstance();     int year = cal.get(Calendar.YEAR);     int month = cal.get(Calendar.MONTH) + 1;     int day = cal.get(Calendar.DAY_OF_MONTH);     int hour = cal.get(Calendar.HOUR_OF_DAY);     int minute = cal.get(Calendar.MINUTE);     int second = cal.get(Calendar.SECOND);     System.out.println("===年===" + year);     System.out.println("===月===" + month);     System.out.println("===日===" + day);     System.out.println("===时===" + hour);     System.out.println("===分===" + minute);     System.out.println("===秒===" + second);   } }

希望本文所述对大家的java程序设计有所帮助。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表