java中常見的日期時間類

來源:互聯網
上載者:User


Date 類: 最基礎的日期時間類,返回一個相對日期的毫秒數。精確到毫秒,但不支援日期的國際化和分時區顯示。
Calender類: 相對於Date更加強大的時間類,是抽象類別,提供了常規的日期修改功能和國際化支援。
GregorianCalendar類: 提供處理日期的方法,用於計算日期,是Calendar類的子類,有用的是有個判斷閏年的方法。
DateFormat類: 可以接受字串輸入 輸出,提供了將日期/時間資訊進行格式化處理的功能。
SimpleDateFormat類: 功能更強大的日期時間格式化類,自訂格式化日期和時間。
java.util.Locale類: 描述特定的地理、政治、文化上的地區,Locale對象主要封裝了“地區”和“語言種類”兩方面 .

使用案列:
1.擷取目前時間

public String GetCurTime()//獲得目前時間
{
Date now=new Date();
return now.getHours()+":"+now.getMinutes()+":"+now.getSeconds();
}
public String GetCurDate()//獲得當前日期
{
Calendar cal=Calendar.getInstance();
return cal.get(Calendar.YEAR)+"年"+(cal.get(Calendar.MONTH)+1)+"月"+cal.get(Calendar.DATE)+"日";
}

2.擷取一月前時間
calendar = Calendar.getInstance();
calendar.add(Calendar.MONTH, -1);

3.擷取一年前時間
calendar = Calendar.getInstance();
calendar.add(Calendar.YEAR, -1);

4.擷取相對日期的毫秒數
Calendar calendar = Calendar.getInstance();
long nowTime = calendar.getTime().getTime();

5.轉換字串為日期
String strDate = "2011-08-13";
SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date sDate = sDateFormat.parse(strDate);

6.格式化顯示日期型資料
Date dt_in :日期型資料
boolean bShowTimePart_in : 是否顯示時間部分
@return String 格式化後的日期格式
*/
public String DoFormatDate(java.util.Date dt_in, boolean bShowTimePart_in) {
if (bShowTimePart_in)
return (new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")).format(dt_in);
else
return (new SimpleDateFormat("yyyy-MM-dd")).format(dt_in);
}

7.判斷閏年
使用java.util.GregorianCalendar類:是Calendar類的子類,有用的是有個判斷閏年的方法。
public void testGregorianCalendar(){
GregorianCalendar gc = new GregorianCalendar();
System.out.println(gc.isLeapYear(2008));
System.out.println("------------------------");
}

8.國際化,資訊通常用於在國際化和本地化程式中的地區、語言相關的方式顯示日期、數字或文本資訊等
public void testLocale(){
Locale defaultLocale = Locale.getDefault(); //當前機器所在的國家和地區
System.out.println(defaultLocale);
System.out.println(defaultLocale.getLanguage()); //英文宿寫的語言名
System.out.println(defaultLocale.getCountry()); //英文宿寫的國家名
System.out.println(defaultLocale.getDisplayName()); //語言名(國家名)
System.out.println(defaultLocale.getDisplayLanguage()); //語言名
System.out.println(defaultLocale.getDisplayCountry()); //國家名
System.out.println("--------------------------");
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.