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;
    }

 

posted @ 2015-01-08 21:23  Porbonan  阅读(406)  评论(2编辑  收藏  举报