JAVA中關於日期的最常見的操作

來源:互聯網
上載者:User

標籤:通過   mat   gettime   isa   操作   exception   try   system   print   

//擷取當前系統的時間戳記        long times = System.currentTimeMillis();        //建立一個當前日期對象        Date now = new Date();        //基於指定的時間戳記建立一個日期對象        Date date = new Date(times - 24*60*60*1000);        //判斷日期now是否在date之前        boolean isBefore = now.before(date);        //判斷日期now是否在date之後        boolean isAfter = now.after(date);        //根據指定的日期格式字串轉換為Date日期對象        String str = "2017-10-12 13:22:32";        DateFormat fd = new SimpleDateFormat("yyyy-MM-dd HH:mm:dd");        try {            date = fd.parse(str);        } catch (ParseException e) {            e.printStackTrace();        }        //將日期對象轉換為指定的日期格式字串        String formatDateStr = fd.format(date);        //擷取指定日期的時間戳記        times = date.getTime();        ////////////////////////////////////////////////////        //建立一個日曆對象        Calendar cal = Calendar.getInstance();        //擷取年        int year = cal.get(Calendar.YEAR);        //擷取月 ,注意其傳回值為0-11        int month = cal.get(Calendar.MONTH) + 1;        //擷取日        int day = cal.get(Calendar.DATE);        //擷取小時,12小時制        int hour = cal.get(Calendar.HOUR);        //擷取小時,24小時制        int fullHour = cal.get(Calendar.HOUR_OF_DAY);        //擷取分鐘數        int minute = cal.get(Calendar.MINUTE);        //擷取秒        int second = cal.get(Calendar.SECOND);        //擷取星期幾,傳回值為0-6,其中0代表星期天        int dayOfWeek= cal.get(Calendar.DAY_OF_WEEK);        //設定日曆對象的年        cal.set(Calendar.YEAR,2018);        //設定日曆對象的其他屬性參考年的設定        //讓指定的日曆對象月份加2,即得到2個月後的日曆對象        cal.add(Calendar.MONTH,2);        //讓指定的日曆對象月份減2,即得到2個月前的日曆對象        cal.add(Calendar.MINUTE,-2);        //通過日曆對象擷取日期對象        Date dateByCal = cal.getTime();

 

JAVA中關於日期的最常見的操作

聯繫我們

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