java 中Date 時間轉換

來源:互聯網
上載者:User
package test;import java.text.ParseException;import java.text.SimpleDateFormat;public class TestDate {public static void main(String[] args) throws ParseException {java.util.Date uDate = new java.util.Date();java.sql.Date sDate = new java.sql.Date(0);SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd");SimpleDateFormat sdfTime = new SimpleDateFormat("HH:mm:ss");SimpleDateFormat sdfDatetime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 把util包中的Date轉換為sql.DateuDate.getTime(); // 擷取longsDate = new java.sql.Date(uDate.getTime());// getParameter是字串,字串日期"2017-08-08"轉換為java.sql.Date// 1. 通過SimpleDateFormat.parse(String str)將字串日期 轉換為 java.util.Date// 2. 通過java.util.Date.getTime() 獲得long型// 3. new java.sql.Date(java.util.Date.getTime());java.util.Date juDate = sdfDate.parse("2017-8-1");long lDate = juDate.getTime();java.sql.Date jsDate = new java.sql.Date(lDate);System.out.println(juDate);System.out.println(lDate);System.out.println(jsDate);System.out.println(sDateToSqldate(null, "yyyy-MM-dd HH:mm:ss", "1990-1-1 0:0:0"));}public static java.sql.Timestamp sDateToSqldate(String date, String pattern, String defaultDate) {try {SimpleDateFormat sdf = new SimpleDateFormat(pattern);long lDate = sdf.parse(date != null ? date : defaultDate).getTime();return new java.sql.Timestamp(lDate);} catch (ParseException e) {e.printStackTrace(); }return null;}}
java.sql.Date類型的日期Date 的構造方法 : Date(long date),需要一個Long型的日期date,而我們做的項目從頁面擷取(getParameter)的日期date都是字串型的,

第一步需要我們把字串日期date轉換為util類型的日期date,需要日期的格式化: SimpleDateFormat

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

java.util.Date juDate = sdf.parse("2017-8-1 20:32:25");

第二步把util類型的日期date變換為Long型Date

juDate.getTime()

第三步把Long型date轉換為sql類型 用的是sql類型date的構造方法
new java.sql.Date(juDate.getTime()); SimpleDateFormat類常用方法

NO 方法 類型 描述
1 public SimpleDateFormat(String pattern) 構造 構建使用預設 FORMAT 地區設定給定的模式和預設日期格式符號 SimpleDateFormat。
2 public final String format(Date date) 普通 將日期格式化為字串資料
3 public Date parse(String source) throws ParseException 普通 將字串格式為日期資料

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.