java中字串與日期的轉換執行個體_java

來源:互聯網
上載者:User

複製代碼 代碼如下:

import java.sql.Timestamp;
import java.text.DateFormat;

import java.text.ParseException;

import java.text.SimpleDateFormat;

import java.util.Date;

public class DateIO {

public static void main(String[] args) {

Date date= new  DateIO().strToDate("2013-04-01");

String strdate=new DateIO().dateToStr(date);

String srrdate=new DateIO().timestampToStr(System.currentTimeMillis());

Timestamp ts=new DateIO().strToTimestamp(new Date());

}

//String 轉換為 Date

public Date strToDate(String strdate){

DateFormat format = new SimpleDateFormat("yyyy-MM-dd"); 

Date date = null;   

try {

date = format.parse(strdate);

} catch (ParseException e) {

e.printStackTrace();

}

System.out.println("date:"+date);

return date;

}

//Date 轉換為 String

public String dateToStr(Date date){


//年月日****-**-**

DateFormat format = new SimpleDateFormat("yyyy-MM-dd"); 

String str = format.format(date);   

System.out.println("str:"+str);


//年月日**-*-*

format = DateFormat.getDateInstance(DateFormat.SHORT);     

str = format.format(date);  

System.out.println(str); 


//年月日****-*-*

format = DateFormat.getDateInstance(DateFormat.MEDIUM);     

str = format.format(date); 

System.out.println(str); 


//****年*月*日星期*

format = DateFormat.getDateInstance(DateFormat.FULL);     

str = format.format(date);

System.out.println(str); 

return str;

}


//Timestamp轉換為String

public String timestampToStr(Long timestamp){

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//定義格式,不顯示毫秒 

String str = df.format(timestamp); 

System.out.println(str); 

return str;

}

//Date轉換為Timestamp

public Timestamp strToTimestamp(Date date){

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

String time = df.format(date); 

Timestamp ts = Timestamp.valueOf(time); 

System.out.println(ts); 

return ts;

}

}

聯繫我們

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