起因:写代码的时候经常会用到获取当前时间戳和日期,现总结如下
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
|
//SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
Date date = new Date();
String dateString = date.toString();
long times = date.getTime();
System.out.println( "date.toString():" +date.toString());
System.out.println( "当前时间戳(毫秒):" + times);
Calendar c = Calendar.getInstance();
System.out.println( "当前日期:" + c.get(Calendar.DATE));
System.out.println( "当前年份:" + c.get(Calendar.YEAR));
//月份从0开始,0-11
System.out.println( "当前月份:" + c.get(Calendar.MONTH));
//12小时制,0-11
System.out.println( "12小时制:当前小时:" + c.get(Calendar.HOUR));
System.out.println( "24小时制:当前小时:" + c.get(Calendar.HOUR_OF_DAY));
System.out.println( "当前分钟:" + c.get(Calendar.MINUTE));
System.out.println( "当前秒:" + c.get(Calendar.SECOND));
System.out.println( "一年中的某天:" + c.get(Calendar.DAY_OF_YEAR));
System.out.println( "当前时间戳(毫秒):" + c.getTimeInMillis());
System.out.println( "Calendar的toString()方法一般用作调试:" +c.toString());
SimpleDateFormat df = new SimpleDateFormat( "yyyyMMdd" );
String currentDateStr = df.format( new Date());
System.out.println( "当前日期yyyyMMdd:" +currentDateStr);
}
<br><br>
|
输出结果:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
date.toString():Wed Aug 02 11 : 39 : 05 CST 2017
当前时间戳(毫秒): 1501645145298
当前日期: 2
当前年份: 2017
当前月份: 7
12 小时制:当前小时: 11
24 小时制:当前小时: 11
当前分钟: 39
当前秒: 5
一年中的某天: 214
当前时间戳(毫秒): 1501645145302
Calendar的toString()方法一般用作调试:java.util.GregorianCalendar[time= 1501645145302 ,areFieldsSet= true ,areAllFieldsSet= true ,lenient= true ,zone=sun.util.calendar.ZoneInfo[id= "Asia/Shanghai" ,offset= 28800000 ,dstSavings= 0 ,useDaylight= false ,transitions= 19 ,lastRule= null ],firstDayOfWeek= 1 ,minimalDaysInFirstWeek= 1 ,ERA= 1 ,YEAR= 2017 ,MONTH= 7 ,WEEK_OF_YEAR= 31 ,WEEK_OF_MONTH= 1 ,DAY_OF_MONTH= 2 ,DAY_OF_YEAR= 214 ,DAY_OF_WEEK= 4 ,DAY_OF_WEEK_IN_MONTH= 1 ,AM_PM= 0 ,HOUR= 11 ,HOUR_OF_DAY= 11 ,MINUTE= 39 ,SECOND= 5 ,MILLISECOND= 302 ,ZONE_OFFSET= 28800000 ,DST_OFFSET= 0 ]
当前日期yyyyMMdd: 20170802
|
总结
以上所述是小编给大家介绍的Java时间类Date类和Calendar类的使用详解,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!
原文链接:http://www.cnblogs.com/zhaijing/archive/2017/08/02/7273013.html