• Date、String和Timestamp类型转换


    1StringDate类型转换:

    1、获取当前系统时间:

    Date date1 = new Date();   //获取系统当前时间

    Calendar cal = Calendar.getInstance();

    Date t = cal.getTime();  //获取系统当前时间

    System.currentTimeMillis(); //获取系统当前时间毫秒数

    2Date类型转换为String类型:

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");

    SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd");

    String str = sdf.format(date1);

    String str1 =sdf1.format(date1); 

    System.out.println(str);

    System.out.println(str1);  

    说明:sdfsdf1只是两个不懂的格式化类型的定义,类型可以自由定义。

    效果如下:

       3String类型转换为Date类型:

    String str2 = "2011-02-02 12:12:12";

    SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");

    SimpleDateFormat sdf3 = new SimpleDateFormat

    ("yyyy-MM-dd HH:mm:ss");

    Date date3 = sdf2.parse(str2);

    Date date4 = sdf3.parse(str2);

    System.out.println(date3);

    System.out.println(date4);

    说明:sdf2sdf3的格式要求,区别是时间部分,另不可在格式化中出现中文字符。

    String str4 = "2012-01-04";

    //只显示日期部分

    System.out.println(java.sql.Date.valueOf(str4));

       

    由于Date类型只能显示时间部分,而无法显示时间不分,因而出现了timestamp类型。

    2StringTimestamp类型转换:

    1String转换为Timestamp类型:

    String str3 = "2011-02-02 12:12:12";

    Timestamp.valueOf(str3);

    System.out.println(Timestamp.valueOf(str3));

      2、timestamp转换为string类型

    Long l = System.currentTimeMillis();

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

    System.out.println(Timestamp.valueOf(format.format(l)));

  • 相关阅读:
    在window10系统下安装redis
    Dubbo 基础用法
    vue处理对象值改变时dom值没有跟着变化的问题
    KMP算法
    Leetcode 502 IPO
    vue页面无法正常渲染的问题
    vue锚点双向绑定
    JavaScript克隆一个对象
    el-table刷新后table出现抖动现象
    el-table组件去掉滚动条的问题
  • 原文地址:https://www.cnblogs.com/onlymate/p/4807539.html
Copyright © 2020-2023  润新知