多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
## Java专题十:日期与时间 [TOC] ### 10.1.java.util.Date类 | 时间 | 说明 | | --- | --- | | year | y - 1900 | | month | [0 - 11] | | date (day of month) | [1 - 31] | | hour | [0 - 23] | | minute | [0 - 59] | | second | [0 - 61] | java.util.Date类中方法说明: | 方法 | 说明 | | --- | --- | |public Date() | 构造当前时间的Date | |public Date(long date) | 根据毫秒值构造Date | |public long getTime() | 获取从January 1, 1970, 00:00:00 GMT起算的毫秒数 | |public int compareTo(Date anotherDate)| 比较2个Date的大小 | ### 10.2.java.util.Calendar类 | 方法 | 说明 | | --- | --- | |public static Calendar getInstance() | 构造当前时间的Calendar | |public int get(int field) | 获取字段,见代码2-1| |public void set(int field, int value)| 设置字段值| |public final Date getTime() | Calendar转换成Date对象 | |public final void setTime(Date date)| Date转换成Calendar对象 | |public long getTimeInMillis()| 获取毫秒数 | |public void setTimeInMillis(long millis) | 设置毫秒数 | |public void add(int field, int amount) | 自动重新计算日期,见代码2-2 | 代码2-1: ``` Calendar cal = Calendar.getInstance(); cal.get(Calendar.YEAR); // year // JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, // AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER, UNDECIMBER cal.get(Calendar.MONTH) + 1; // month cal.get(Calendar.DATE); // day cal.get(Calendar.HOUR_OF_DAY); // hour cal.get(Calendar.MINUTE); // minute cal.get(Calendar.SECOND); // second cal.get(Calendar.MILLISECOND); // millisecond // AM = 0, PM = 1 cal.get(Calendar.AM_PM); // MONDAY = 2, TUESDAY = 3, WEDNESDAY = 4, THURSDAY = 5, // FRIDAY = 6, SATURDAY = 7, SUNDAY = 1 cal.get(Calendar.DAY_OF_WEEK); ``` 代码2-2: ``` Calendar cal = Calendar.getInstance(); df.format(cal.getTime()); // 2020-03-20 cal.add(Calendar.DATE, 13); // 重新计算 df.format(cal.getTime()); // 2020-04-02 ``` ### 10.3.java.text.SimpleDateFormat类 #### 10.3.1.format方法:将Date和毫秒数转换成String类型 - String format(Date date) - String format(milliseconds) ``` SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); df.format(new Date()); df.format(System.currentTimeMillis()); df.format(Calendar.getInstance().getTime()); ``` #### 10.3.2.parse方法:将String类型转换成Date类型 - Date parse(String source) throws ParseException ``` SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String formatTime = df.format(System.currentTimeMillis()); Date d = df.parse(formatTime); ```