java.sql.Date和java.sql.Timestamp转换

在开发web应用中,针对不同的数据库日期类型,我们需要在我们的程序中对日期类型做各种不同的转换。若对应数据库数据是oracle的Date类型,即只需要年月日的,可以选择使用java.sql.Date类型,若对应的是MSsqlserver数据库的DateTime类型,即需要年月日时分秒的,选择java.sql.Timestamp类型
你可以使用dateFormat定义时间日期的格式,转一个字符串即可

package personal.jessica;
import java.util.Date;
import java.util.Calendar;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Locale;
class Datetest{
 /**
  *method 将字符串类型的日期转换为一个timestamp(时间戳记java.sql.Timestamp)
  *@param dateString 需要转换为timestamp的字符串
  *@return dataTime timestamp
  */
 public final static java.sql.Timestamp string2Time(String dateString)
  throws java.text.ParseException {
   DateFormat dateFormat;
  dateFormat = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss.SSS", Locale.ENGLISH);//设定格式
  //dateFormat = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss", Locale.ENGLISH);
  dateFormat.setLenient(false);
  java.util.Date timeDate = dateFormat.parse(dateString);//util类型
  java.sql.Timestamp dateTime = new java.sql.Timestamp(timeDate.getTime());//Timestamp类型,timeDate.getTime()返回一个long型
  return dateTime;
 }
 /**
  *method 将字符串类型的日期转换为一个Date(java.sql.Date)
  *@param dateString 需要转换为Date的字符串
  *@return dataTime Date
  */
 public final static java.sql.Date string2Date(String dateString)
  throws java.lang.Exception {
  DateFormat dateFormat;
  dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
  dateFormat.setLenient(false);
  java.util.Date timeDate = dateFormat.parse(dateString);//util类型
  java.sql.Date dateTime = new java.sql.Date(timeDate.getTime());//sql类型
  return dateTime;
 }
 
 public static void main(String[] args){
  Date da = new Date();
  //注意:这个地方da.getTime()得到的是一个long型的值
  System.out.println(da.getTime());
  
  //由日期date转换为timestamp
  
  //第一种方法:使用new Timestamp(long)
  Timestamp t = new Timestamp(new Date().getTime());
  System.out.println(t);

  //第二种方法:使用Timestamp(int year,int month,int date,int hour,int minute,int second,int nano)
  Timestamp tt = new Timestamp(Calendar.getInstance().get(
      Calendar.YEAR) - 1900, Calendar.getInstance().get(
      Calendar.MONTH), Calendar.getInstance().get(
      Calendar.DATE), Calendar.getInstance().get(
      Calendar.HOUR), Calendar.getInstance().get(
      Calendar.MINUTE), Calendar.getInstance().get(
      Calendar.SECOND), 0);
  System.out.println(tt);

  try {
   String sToDate = "2005-8-18";//用于转换成java.sql.Date的字符串
      String sToTimestamp = "2005-8-18 14:21:12.123";//用于转换成java.sql.Timestamp的字符串
      Date date1 = string2Date(sToDate);
      Timestamp date2 = string2Time(sToTimestamp);
   System.out.println("Date:"+date1.toString());//结果显示
   System.out.println("Timestamp:"+date2.toString());//结果显示
  }catch(Exception e) {
   e.printStackTrace();
  }
 }
}

怎样处理一个时间段,比如某人登陆了xx天xx小时xx分xx秒

这个问题可以如下处理:
首先你肯定可以从数据库中读取这个用户第一次登陆的具体时间:
不妨为2002-01-01 12:00:00
同样他到目前为止最后登陆的具体时间:
不妨为2002-09-08 13:14:15
若取得是数据本来就是时间类型的,则不用转化,若是String的则可以在转化后处理。
你可以利用类似上面的例子,取得这两个时间对应的Timestamp值dateTime
然后使用dateTime.getTime()方法得到这两个时间的long值,进行相减(大的减小的,即按时间后减先),得到一个long值,它是用毫秒milliseconds计算的,你将它换算一下就知道多少天多少小时多少分多少秒了
比如首先除于(java中/除)一天的毫秒数,得到天,然后用余下的值除于一小时的毫秒数,得到小时……最后就可以得到所有的需求了

 

java语言对时间的处理
.处理数据库,有DATE Java.sql.Date 日期,
TIME Java.sql.Time 时戳,TIMESTAMP Java.sql.Timestamp 当日日期和时间,
对应的ResultSet的方法
DATE                          java.sql.Date                               java.sql.Date getDate()
TIME                           java.sql.Time                               java.sql.Time getTime()
TIMESTAMP              java.sql.Timestamp                   java.sql.Timestamp getTimestamp()
根据java2的规范要求使用Java.sql.Timestamp,这样不会失去精度详见( http://blogger.org.cn/blog/more.asp?name=hongrui&id=7557)。对于oracle数据库比较例外,可以用oracle.sql.TIMESTAMP
这和他的版本也有关系。 注意,SQLserver中timestamp 对应的是 DateTime类型。
使用spring的jdbc时,尽可能用Java.sql.Timestamp详见( http://blogger.org.cn/blog/more.asp?name=hongrui&id=9521)。
下面给个例子
public static java.sql.Timestamp getDBSysdate(Connection conn)
throws Exception {
Statement stmt = null;
ResultSet rs = null;
Timestamp sysTime = null;

try {
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT SYSDATE FROM DUAL");
if (rs.next()) {
sysTime = rs.getTimestamp("SYSDATE");
}
} catch (Exception e) {

} finally {
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
} catch (Exception e) {

}
}

return sysTime;
}
最好的办法使用long存时间,使用Calendar 处理,就是表示日期时间不直观。
2.字符串转化时间,注意不能判断时间输入是否正确,判断时间输入是否正确,请使用正则。
try
     {
      String st="2005-13-32 12:00";
     java.text.DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm");
              Date  starttime = df.parse(st);
     System.out.println(starttime.toString());       
     }
catch(Exception ex)
{
 
}
不要搞混了try-catch的功能。只有程序或系统抛出了异常,try-catch才能捕获 ,得到Wed Feb 01 00:00:00 CST 2006
这样操作是错误的,Timestamp是java.util.Date,会得到java.lang.ClassCastException,你犯了向下转型的错误。

try
     {
      String st="2005-13-32 12:00";
     java.text.DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm");
              Timestamp  starttime =(Timestamp) df.parse(st);
     System.out.println(starttime.toString());       
     }
catch(Exception ex)
{
 ex.printStackTrace();
}
应该使用
try {
   String st = "2005-12-2 12:00:00";
   Timestamp starttime = Timestamp.valueOf(st);
   System.out.println(starttime.toString());
  } catch (Exception ex) {
   ex.printStackTrace();
  }
  或
  import java.sql.*;
import java.util.*;

public class CreateTimestamp {
   public static void main(String [] args) {

   Calendar cal = Calendar.getInstance();

   cal.set(Calendar.YEAR, 2000);
   cal.set(Calendar.MONTH, Calendar.JANUARY);
   cal.set(Calendar.DATE, 1);
   cal.set(Calendar.HOUR_OF_DAY, 11);
   cal.set(Calendar.MINUTE, 45);
   cal.set(Calendar.SECOND, 30);
   cal.set(Calendar.MILLISECOND, 0);

   long millis = cal.getTime().getTime();
   System.out.println("milliseconds in millis = " + millis);
   java.sql.Timestamp ts = new java.sql.Timestamp(millis);
   System.out.println("Timestamp ts before setting nanos = " + ts);

   ts.setNanos(500);
   System.out.println("Timestamp ts with nanos set = " + ts);
   }
}


下面给出javadoc的方法
1. java.sql.Date.valueOf(java.lang.String)

    public static Date valueOf(String s)
 Converts a string in JDBC date escape format to a Date value.

 Parameters:
 s - a String object representing a date in in the format "yyyy-mm-dd"
 Returns:
 a java.sql.Date object representing the given date
 Throws:
 IllegalArgumentException - if the date given is not in the JDBC date escape format (yyyy-mm-dd)

2. java.sql.Time.valueOf(java.lang.String)

    public static Time valueOf(String s)
 Converts a string in JDBC time escape format to a Time value.

 Parameters:
 s - time in format "hh:mm:ss"
 Returns:
 a corresponding Time object

3. java.sql.Timestamp.valueOf(java.lang.String)
  
   public static Timestamp valueOf(String s)
 Converts a String object in JDBC timestamp escape format to a Timestamp value.

 Parameters:
 s - timestamp in format yyyy-mm-dd hh:mm:ss.fffffffff
 Returns:
 corresponding Timestamp value
 Throws:
 IllegalArgumentException - if the given argument does not have the format yyyy-mm-dd hh:mm:ss.fffffffff

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值