博客
关于我
日期和字符串的相互转换
阅读量:354 次
发布时间:2019-03-04

本文共 1311 字,大约阅读时间需要 4 分钟。

/**

        * 日期转换字符串
        * @param date 日期
        * @param type 显示格式 yyyy-MM-dd yyyy-MM-dd HH:mm:ss
        * String returnvalue = UtilClass.DateToString(this.Startdatetest.getValue(), "yyyy-MM-dd");
        */

public static String dateToString(Object date,String type) {

        String retultValue = "";
        if (date != null) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat(type);

//这里需要注意的是,如果你传入的是String类型的值,需要再次转换,format里面的参数是Date类型的,否则会有  java.lang.IllegalArgumentException: Cannot format given Object as a Date  异常。

              //retultValue = sdf.format(sdf.parse(date));

                retultValue = sdf.format(date);
            } catch (Exception e) {
                 e.printStackTrace();
            }
        }
        return retultValue;
    }

 

/**

     * 字符串转为日期
     * @param DateStr 字符串
     * @param type 类型 "yyyy-MM-dd HH:mm:ss"
     * @return Date  java.util.Date
     */
    public static Date StringToDate(String date,String type) {
        Date resultDate = null;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(type);
            resultDate = sdf.parse(date);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultDate;     
    }

public static void main(String[] args) {

        
        String type = "yyyy-MM-dd HH:mm:ss";//日期格式
        long date = 1559014035000L;//时间戳

           //获取系统当前时间

         // long date = System.currentTimeMillis();

        // Date date = new Date();

//        Date riqi = StringToDate(date, type);
//        System.out.println(riqi);
        String shiJian = dateToString(date, type);
        System.out.println(shiJian);
    }

转载地址:http://lskr.baihongyu.com/

你可能感兴趣的文章
MySQL中一条SQL语句到底是如何执行的呢?
查看>>
MySQL中你必须知道的10件事,1.5万字!
查看>>
MySQL中使用IN()查询到底走不走索引?
查看>>
Mysql中使用存储过程插入decimal和时间数据递增的模拟数据
查看>>
MySql中关于geometry类型的数据_空的时候如何插入处理_需用null_空字符串插入会报错_Cannot get geometry object from dat---MySql工作笔记003
查看>>
mysql中出现Incorrect DECIMAL value: '0' for column '' at row -1错误解决方案
查看>>
mysql中出现Unit mysql.service could not be found 的解决方法
查看>>
mysql中出现update-alternatives: 错误: 候选项路径 /etc/mysql/mysql.cnf 不存在 dpkg: 处理软件包 mysql-server-8.0的解决方法(全)
查看>>
Mysql中各类锁的机制图文详细解析(全)
查看>>