本文实例讲述了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程序设计有所帮助。
本文地址:https://www.stayed.cn/item/24693
转载请注明出处。
本站部分内容来源于网络,如侵犯到您的权益,请 联系我