zoukankan      html  css  js  c++  java
  • JAVA里的String、Timestamp、Date相互转换

    Timestamp转化为String:

    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//定义格式,不显示毫秒
    Timestamp now = new Timestamp(System.currentTimeMillis());//获取系统当前时间
    String str = df.format(now);
     
    String转化为Timestamp:
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String time = df.format(new Date());
    Timestamp ts = Timestamp.valueOf(time);
    注:当表单里的时间没有秒时,应先将String转化为Date类型,再转化为Timestamp。
    代码如下:
    SimpleDateFormat df = new Simple("yyyy-MM-dd HH:mm");
    Date date = df.parse(String);
    Timestamp ts = new Timestamp(date.getTime());
     
    Date、String、Timestamp之间的转换!

    Date 和String之间的转换main函数:
    public static void main(String[] args) {
       // TODO Auto-generated method stub
    DateFormat format = new SimpleDateFormat("yyyy-MM-dd");        
    Date date = null;   
    String str = null;                 
                
    // String转Date   
    str = "2009-01-06";         
    try {   
    date = format.parse(str); // Wed sep 26 00:00:00 CST 2007   
    } catch (ParseException e) {   
    e.printStackTrace();   
    }   
              
    date = java.sql.Date.valueOf(str); // 只保留日期部分,返回的是java.sql.Date 2007-9-26
    System.out.println(date);


    // Date转String   
    date = new Date();   // Wed sep 26 18 17:14:01 CST 2007      
    str = format.format(date); // 2007-9-26   
                 System.out.println(str);
    format = DateFormat.getDateInstance(DateFormat.SHORT);   
    str = format.format(date); // 07-9-26
    System.out.println(str);
               
    format = DateFormat.getDateInstance(DateFormat.MEDIUM);   
    str = format.format(date); // 2007-9-26  
                     System.out.println(str);
          format = DateFormat.getDateInstance(DateFormat.FULL);   
            str = format.format(date); // 2007年9月26日 星期三
       System.out.println(str);
    }

    Timestamp和String之间转换的函数:
    public static void main(String[] args) {
       // TODO Auto-generated method stub
       //Timestamp转化为String:
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//定义格式,不显示毫秒
        Timestamp now = new Timestamp(System.currentTimeMillis());//获取系统当前时间
        String str = df.format(now);
        System.out.println(str);
        
        ///String转化为Timestamp:
        SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        String time = df1.format(date);
        Timestamp ts = Timestamp.valueOf(time);
        System.out.println(ts);

    }

  • 相关阅读:
    实验 4:Open vSwitch 实验——Mininet 中使用 OVS 命令
    实验 3:Mininet 实验——测量路径的损耗率
    软工第一次作业
    实验2:Mininet实验——拓扑的命令脚本生成
    实验 1:Mininet 源码安装和可视化拓扑工具
    AU降噪处理
    软件测试,Homework3
    软件测试,Lab1
    软件测试,Homework2
    node.js,同时访问出错,Can't set headers after they are sent
  • 原文地址:https://www.cnblogs.com/franson-2016/p/5664539.html
Copyright © 2011-2022 走看看