1、Date对象转换为时间戳

Date date = new Date();  
long times = date.getTime();  
System.out.println(times);  

   效果如下:

1508824283292

 

2、时间戳转换为Date日期对象

long times = System.currentTimeMillis();  
Date date = new Date(times);  
System.out.println(date); 

  效果如下:

Tue Oct 24 13:49:28 CST 2017

 

3、时间戳转换为指定日期格式

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long times = System.currentTimeMillis();  
String str = format.format(times);
System.out.println(str); 

  效果如下:

2017-10-24 13:50:46

 

4、时间字符串<年月日时分秒毫秒 >转为 时间戳

20180914150324
转为
1536908604990

 

代码:

//大写HH:24小时制,小写hh:12小时制
//毫秒:SSS
//指定转化前的格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
//转化后为Date日期格式
Date date = sdf.parse(sb.toString());
//Date转为时间戳long
long shootTime = date.getTime();
System.out.println(shootTime);

 

 

 

 

实例:获取数据库的BigInt类型的时间戳,并转为日期格式

package com.test;

import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Calendar;

public class Test {

    

    public static void main(String[] args) {
         
         Connection conn;
         Statement stmt;
         ResultSet rs;
         String url = "jdbc:sqlserver://localhost:1433;DatabaseName=test;";
         String sql = "select * from [test].[dbo].[student]";
         try {
             conn = DriverManager.getConnection(url, "sa", "Rfid123456");
             stmt = conn.createStatement();
             rs = stmt.executeQuery(sql);
             while(rs.next()){
                 
                 long times = rs.getLong("date");
                 System.out.println(times);
                 
                 Date date  =  new Date(times);
                 System.out.println(date);
                 
             }
             
             if (rs != null) {
                 rs.close();
                 rs = null;
             }
             
             if (stmt != null) {
                 stmt.close();
                 stmt = null;
             }
             if (conn != null) {
                 conn.close();
                 conn = null;
             }
         } catch (SQLException e) {
             e.printStackTrace();
             System.out.println("数据库连接失败");
         }

    }
    
}

 

 posted on 2017-10-13 17:31  布鲁布鲁sky  阅读(25971)  评论(1编辑  收藏  举报