萬盛學電腦網

 萬盛學電腦網 >> 網絡編程 >> 編程語言綜合 >> Java獲取時間年、月、日的方法

Java獲取時間年、月、日的方法

   本文實例講述了Java獲取時間年、月、日的方法。分享給大家供大家參考。具體實現方法如下:

  ?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 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程序設計有所幫助。

copyright © 萬盛學電腦網 all rights reserved