咱們將討論下面的類:
一、具體類(和抽象類相對)java.util.Date
二、抽象類java.text.DateFormat 和它的一個具體子類,java.text.SimpleDateFormat
三、抽象類java.util.Calendar 和它的一個具體子類,java.util.GregorianCalendar java
在 JDK 1.1 以前,類 Date 有兩個其餘的函數。它容許把日期解釋爲年、月、日、小時、分鐘和秒值。它也容許格式化和分析日期字符串。不過,這些函數的 API 不易於實現國際化。從 JDK 1.1 開始,應該使用 Calendar 類實現日期和時間字段之間轉換,使用 DateFormat 類來格式化和分析日期字符串。Date 中的相應方法已廢棄。 dom
具體的我就不說了!您看下下面的代碼,再去看看API就懂他們經常使用了!ide
- package com.hanchao.test;
- import java.text.SimpleDateFormat;
- import java.util.Calendar;
- import java.util.Date;
- import java.util.GregorianCalendar;
- import java.util.Random;
- /**
- * 來測試一下此類:GregorianCalendar
- * @author hanlw
- */
- public class Test {
- public static void main(String[] args) {
- /*****************************************
- * 經過GregorianCalendar能夠獲取年月日時分秒的各自的值
- */
- GregorianCalendar cal = new GregorianCalendar();
- int curYear = cal.get(Calendar.YEAR);
- int curMonth = cal.get(Calendar.MONTH)+1;
- int curDate = cal.get(Calendar.DATE);
- int curHour = cal.get(Calendar.HOUR_OF_DAY);
- int curMinute = cal.get(Calendar.MINUTE);
- System.out.println(curYear + "年\t"
- + curMonth + "月\t"
- + curDate +"日\t"
- + curHour + "時\t"
- + curMinute + "分\n");
- /**********************************************
- * Date的方法用的比較少了!用的比較少了!
- */
- Date date = new Date();
- System.out.println("系統當前的時間:"+date.getTime() + "\n");
- /************************************************
- * 經常使用到的。 注意大小寫的區別啊!!
- */
- SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd" + "\n");
- System.out.println("今天的日期爲:\t"+sdf.format(date));
- SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM" + "\n");
- System.out.println("輸出年月:\t" +sdf2.format(date));
- SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd HH");
- System.out.println("某年月某日某時:\t" +sdf3.format(date) + "\n");
- SimpleDateFormat sdf4 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
- System.out.println("某年某月某日某時某分:\t" + sdf4.format(date) +"\n");
- SimpleDateFormat sdf5 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- System.out.println("某年某月某日某時某分某秒:\t" + sdf5.format(date));
- SimpleDateFormat sdf6 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:ms");
- System.out.println("某年某月某日某時某分某秒某毫秒:\t" + sdf6.format(date)+"\n");
- /** 看看電子商務網站的訂單的生成吧。*/
- System.out.println("您的訂單號:\t" +getNow() + "\n");
- }
- /**
- * 該方法經常使用來生成訂單
- * @return
- */
- public static String getNow() {
- SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssms");//時間格式
- //是隨機數的生成(保證那一秒鐘訂單的不重複,若是您的業務量很是大時,咱們能夠把下面的1000改爲10000000......)
- Random random = new Random();
- int index = random.nextInt(1000);
- return sdf.format(new Date())+index;//返回當前時間對應的字符串+一個1000之內隨機
- }
- }
具體的運行結果爲:函數