字串 與 java.sql.Timestamp轉換部落格分類: javaJavaSQL

來源:互聯網
上載者:User

package test;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
* 時間戳記與字串轉換
* @author Administrator
*
*/
public class DateUtil {

/**
* 預設日期格式
*/
private static final String DEFAULT_FORMAT = "yyyy-MM-dd HH:mm:ss.SSS";//Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff]

/**
* 預設建構函式
*/
private DateUtil() {
}

/**
* 字串轉換成日期 如果轉換格式為空白,則利用預設格式進行轉換操作
* @param str 字串
* @param format 日期格式
* @return 日期
* @throws java.text.ParseException
*/
public static Date str2Date(String str, String format){
if (null == str || "".equals(str)) {
return null;
}
// 如果沒有指定字串轉換的格式,則用預設格式進行轉換
if (null == format || "".equals(format)) {
format = DEFAULT_FORMAT;
}
SimpleDateFormat sdf = new SimpleDateFormat(format);
Date date = null;
try {
date = sdf.parse(str);
return date;
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}

/** 日期轉換為字串
* @param date 日期
* @param format 日期格式
* @return 字串
*/
public static String date2Str(Date date, String format) {
if (null == date) {
return null;
}
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.format(date);
}

/**
* 時間戳記轉換為字串
* @param time
* @return
*/
public static String timestamp2Str(Timestamp time) {
Date date = null;
if(null != time){
date = new Date(time.getTime());
}
return date2Str(date, DEFAULT_FORMAT);
}

/** 字串轉換時間戳記
* @param str
* @return
*/
public static Timestamp str2Timestamp(String str) {
Date date = str2Date(str, DEFAULT_FORMAT);
return new Timestamp(date.getTime());
}

public static void main(String[] args) throws Exception {
String tm = "2011-01-01 10:00:00.123";
Timestamp tstamp = str2Timestamp(tm);
System.out.println(tstamp);
System.out.println(timestamp2Str(null));
}
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.