起因:寫代碼的時候經常會用到獲取當前時間戳和日期,現總結如下 date.toString():Wed Aug 02 11:39:05 CST 2017當前時間戳(毫秒):1501645145298當前日期:2當前年份:2017當前月份:712小時制:當前小時:1124小時制:當前小時:11當前分鐘: ...
起因:寫代碼的時候經常會用到獲取當前時間戳和日期,現總結如下
public void testDate() {
//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);
}
輸出結果:
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