天天看點

擷取系統時間的四種方法

1、Date day=new Date();

      SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

      System.out.println(df.format(day));

      通過Date類來擷取目前時間

2、SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

      System.out.println(df.format(System.currentTimeMillis()));

      通過System類中的currentTimeMillis方法來擷取目前時間

3、Calendar c = Calendar.getInstance();//可以對每個時間域單獨修改

        int year = c.get(Calendar.YEAR);

        int month = c.get(Calendar.MONTH);

        int date = c.get(Calendar.DATE);

        int hour = c.get(Calendar.HOUR_OF_DAY);

        int minute = c.get(Calendar.MINUTE);

        int second = c.get(Calendar.SECOND);

        System.out.println(year + "/" + month + "/" + date + " " +hour + ":" +minute + ":" + second);

         通過Calendar類來擷取目前時間

        c.add(Calendar.DAY_OF_YEAR, 1);

        c.set(Calendar.HOUR_OF_DAY, 0);

        c.set(Calendar.MINUTE, 0);

        c.set(Calendar.SECOND, 0);

        c.set(Calendar.MILLISECOND, 0);

4、  Date date = new Date();

        String year = String.format("%tY", date);

        String month = String.format("%tB", date);

        String day = String.format("%te", date);

        System.out.println("今天是:"+year+"-"+month+"-"+day);

        通過Date類來擷取目前時間

總結:

設定時間格式可通過調用SimpleDateFormat類進行設定和通過String中的format方法來設定。

可通過Date類和System中的currentTimeMillis方法來擷取。

或者直接通過Calendar類擷取時間