本文实例讲述了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程序设计有所帮助。