java中字符串与日期的转换实例
复制代码 代码如下: 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; }
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; } 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; } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |