Java時間簡單操作,java操作

來源:互聯網
上載者:User

Java時間簡單操作,java操作

使用java操作時間感覺真真蛋疼,還是我大C#舒服,一個DateTime全部搞定

這裡的Date指的是java.util.Date

擷取目前時間:

        // 建立一個目前時間的Date對象        Date time = new Date();

蛋疼的地方,對時間增、減操作:

        // 使用Calendar類對時間增、減操作        Calendar c = Calendar.getInstance();// 獲得一個Calendar執行個體,該類是抽象類別所以不可以使用new構造方法        // 使用setTime方法建立一個時間,這個time是Date類型        c.setTime(time);        // 為目前時間增加12個月,可根據Calendar枚舉值改變添加單位        c.add(Calendar.MONTH, 12);        // 將Calendar轉為Date對象        Date dateTime = c.getTime();

再次蛋疼的地方,格式化時間,方便人看的格式:

        // 使用SimpleDateFormat對時間格式化為字串形式        String timeStr = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(time);

 

簡單操作,備忘:

方便的時間戳記轉換:

    /**     * 將時間對象轉成時間戳記     *      * @param time     *            時間     * @return 時間戳記     */    public static long DateToLong(Date time) {        try {            long timeL = time.getTime();            System.out.print(timeL);            return timeL;        } catch (Exception e) {            e.printStackTrace();            return 0;        }    }    /**     * 將時間戳記轉為時間對象     *      * @param time     *            時間戳記     * @return 時間對象     */    public static Date LongToDate(long time) {        Date date = null;        try {            date = new Date(time);            System.out.println(date);        } catch (Exception e) {            e.printStackTrace();        }        return 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.