日期格式的转换

来源:互联网 发布:java获取泛型类型 编辑:程序博客网 时间:2024/05/02 00:42

日期格式的转换

转发 http://xialiang19851204.blog.163.com/blog/static/372077352007102744837279/


一、代码:

    /**
     * 毫秒转换成日期格式(例如:1427881379000,运行结果:2015-04-01 17:52:05)
     * @param milliseconds 毫秒数
     * @return 日期
     */
    public static String formatMillisToDate(long milliseconds) {
        try {
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return sf.format(milliseconds);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
    
    /**
     * 日期格式转换成毫秒
     * @param date(例如:2015-04-01 17:52:05,运行结果:1427881379000)
     * @return 毫秒
     */
    public static long formatDateToMillis(String date) {
        try {
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            java.sql.Date dateTime = new java.sql.Date(sf.parse(date).getTime());
            return dateTime.getTime();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return -1;
    }


二、测试代码:

        //输出毫秒
        long milliseconds = formatDateToMillis("2015-04-01 17:52:05");
        System.out.println("Milliseconds=" + milliseconds);

        //输出日期
        String date = formatMillisToDate(milliseconds);
        System.out.println("Date=" + date);


三、注意:java.sql.Date包的引用,若不是全路径引用注意引入的包是否正确;




0 0
原创粉丝点击