A string and date conversion instance in Java

  • 2020-04-01 01:50:36
  • OfStack


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 to 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 converts to String
public String dateToStr(Date date){

//(date) (month) (year) * * * * - * * - * *
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");  
String str = format.format(date);    
System.out.println("str:"+str); 

//(date) (month) (year) * * - * - *
format = DateFormat.getDateInstance(DateFormat.SHORT);      
str = format.format(date);   
System.out.println(str);  

//(date) (month) (year) * * * * - * - *
format = DateFormat.getDateInstance(DateFormat.MEDIUM);      
str = format.format(date);  
System.out.println(str);  

//**** week of **** year **
format = DateFormat.getDateInstance(DateFormat.FULL);      
str = format.format(date);
System.out.println(str);  
return str;
}

//Timestamp is converted to String
public String timestampToStr(Long timestamp){
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//Defines a format that does not show milliseconds & NBSP;
String str = df.format(timestamp);  
System.out.println(str);  
return str;
}

//Date converted to 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;
}
}


Related articles: