Java獲得時光年、月、日的辦法。本站提示廣大學習愛好者:(Java獲得時光年、月、日的辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是Java獲得時光年、月、日的辦法正文
本文實例講述了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法式設計有所贊助。