java工具類Date 日期類應用

來源:互聯網
上載者:User

標籤:格式化   date calender   io   

直接上代碼:

package Test;import java.text.DateFormat;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;public class Test {public static void main(String[] args) {Date date = new Date();// 獲得系統目前時間System.out.println(date);//列印系統目前時間long time = date.getTime();Date d2 = new Date(time);// 使用定義好的日期格式化工具類DateFormat df = DateFormat.getDateInstance(DateFormat.DEFAULT);System.out.println(df.format(date));// 將字串轉換成Date對象try {Date d3 = df.parse("15-03-04");System.out.println(d3);} catch (ParseException e) {// TODO Auto-generated catch blocke.printStackTrace();}// 自訂格式格式化日期和時間// 注意: 月MM 分 mm 秒:ss 毫秒:SSSSimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss:SSS");System.out.println(sdf.format(new Date()));//使用system.currentTimeMillis()擷取目前時間long time2 = System.currentTimeMillis();Date d = new Date(time);System.out.println(d);/*Calendar calendar = Calendar.getInstance();//System.out.println(calendar.toString());//列印獲得的calendarint year = calendar.get(Calendar.YEAR);//擷取年份int month = calendar.get(Calendar.MONTH);//擷取月份int day = calendar.get(calendar.DAY_OF_MONTH);//擷取月份要注意的就是裡面的月份和實際的相差一個月數組的下標是0開始的//指示月份的 get 和 set 的欄位數字。這是一個特定於日曆的值。在格里高利曆和羅馬儒略曆中一年中的第一個月是 JANUARY,它為 0;最後一個月取決於一年中的月份數。int week = calendar.get(Calendar.DAY_OF_WEEK);//擷取daySystem.out.println(year+"-"+month+"-"+day);//列印年月日2015-7-10//System.out.println(year);String[] months = { "1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月" };//如果想要實現列印真實的月份可以這樣實現System.out.println(months[month]);// 0-11這樣就可以列印正確的月份String[] weeks = { "", "Sunday", "Monday", "Tuesday" };//星期儲存的時候因為是老外開發的所以就第一個儲存的是sunday 所以還是和月份一樣的處理方式System.out.println(weeks[week]);System.out.println(calendar.get(Calendar.DAY_OF_MONTH));System.out.println(calendar.get(Calendar.HOUR_OF_DAY));// 24小時String str = String.format("%d年-%d月-%d日", year,month,day);//獲得我們想要的格式的字串System.out.println(str);// %s String %c char %d int %f float double進行格式化的時候要使用到的各種類型System.out.println(String.format("%.2f", 10 / 3.0));對應的結果 *2015-7-108月Monday10212015年-7月-10日3.33 * */}}
希望對大家有用

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

java工具類Date 日期類應用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.