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

    }

  • 相关阅读:
    TCP建立连接三次握手和释放连接四次握手
    集群/分布式环境下5种session处理策略
    MySQL两种引擎的区别
    【深入理解JVM】:类加载器与双亲委派模型
    Spring Cloud组件完整
    用Redis轻松实现秒杀系统
    分布式锁的基本原理
    中文分词-jieba
    win10安装mysql5.7.20解压版
    tenaorflow函数(1)
  • 原文地址:https://www.cnblogs.com/franson-2016/p/5664539.html
Copyright © 2011-2022 走看看