要分别获取时间部分,请使用日期时间字段。
要获取日期,请使用以下字段。
Calendar.YEAR Calendar.MONTH Calendar.DATE
要获取时间,请使用以下字段。
Calendar.HOUR_OF_DAY Calendar.HOUR Calendar.MINUTE Calendar.SECOND Calendar.MILLISECOND
以下是一个示例。
import java.util.Calendar; public class Demo { public static void main(String[] args) { Calendar cal = Calendar.getInstance(); //当前日期和时间 System.out.println(cal.getTime().toString()); //日期信息 System.out.println("\nDate Information.........."); System.out.println("Year = " + cal.get(Calendar.YEAR)); System.out.println("Month = " + (cal.get(Calendar.MONTH) + 1)); System.out.println("Date = " + cal.get(Calendar.DATE)); //时间信息 System.out.println("\nTime Information.........."); System.out.println("Hour (24 hour format) : " + cal.get(Calendar.HOUR_OF_DAY)); System.out.println("Hour (12 hour format) : " + cal.get(Calendar.HOUR)); System.out.println("Minute : " + cal.get(Calendar.MINUTE)); System.out.println("Second : " + cal.get(Calendar.SECOND)); System.out.println("Millisecond : " + cal.get(Calendar.MILLISECOND)); } }
输出结果
Mon Nov 19 14:46:29 UTC 2018 Date Information.......... Year = 2018 Month = 11 Date = 19 Time Information.......... Hour (24 hour format) : 14 Hour (12 hour format) : 2 Minute : 46 Second : 29 Millisecond : 762