一、
获取当前系统时间和日期并格式化输出:
import java.util.Date; import java.text.SimpleDateFormat; public class NowString { public static void main(String[] args) { SimpleDateFormat df = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" ); System.out.println(df.format(new Date())); } }
二、
Date转换为Datetime
Date date = new Date(); Timestamp timestamp = new Timestamp(date.getTime());
三、String转换为Date
String str = "2013-01-14" ; SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd" ); Date date = null ; try { date = sdf.parse(str); } catch (ParseException e) { e.printStackTrace(); }
四、Date转换为String
Date date = new Date(); DateFormat format = new SimpleDateFormat( "yyyy-MM-dd" ); String str = format.format(date);
五、
String转化为java.sql.Date
String str = "2013-01-14" ; SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd" ); java.sql.Date sdate = null ; try { java.util.Date udate = sdf.parse(str); sdate = new java.sql.Date(udate.getTime()); } catch (ParseException e) { e.printStackTrace(); }
六、SimpleDateFormat格式说明
G 年代标志符 y 年 M 月 d 日 h 时 在上午或下午 (1~12) H 时 在一天中 (0~23) m 分 s 秒 S 毫秒 E 星期 D 一年中的第几天 F 一月中第几个星期几 w 一年中第几个星期 W 一月中第几个星期 a 上午 / 下午 标记符 k 时 在一天中 (1~24) K 时 在上午或下午 (0~11) z 时区
import java.text.*; import java.util.Date; public class FormatDateTime { public static void main(String[] args) { SimpleDateFormat myFmt=new SimpleDateFormat( "yyyy年MM月dd日 HH时mm分ss秒" ); SimpleDateFormat myFmt1=new SimpleDateFormat( "yy/MM/dd HH:mm" ); SimpleDateFormat myFmt2=new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" ); SimpleDateFormat myFmt3=new SimpleDateFormat( "yyyy年MM月dd日 HH时mm分ss秒 E " ); SimpleDateFormat myFmt4=new SimpleDateFormat( "一年中的第 D 天 一年中第w个星期 一月中第W个星期 在一天中k时 z时区" ); Date now=new Date(); System.out.println(myFmt.format(now)); System.out.println(myFmt1.format(now)); System.out.println(myFmt2.format(now)); System.out.println(myFmt3.format(now)); System.out.println(myFmt4.format(now)); System.out.println(now.toGMTString()); System.out.println(now.toLocaleString()); System.out.println(now.toString()); } }
七、将Unix时间戳转换成指定格式日期
public String TimeStamp2Date(String timestampString, String formats){ Long timestamp = Long.parseLong(timestampString)*1000 ; String date = new java.text.SimpleDateFormat(formats).format( new java.util.Date(timestamp)); return date; }
当调用TimeStampToDate("1252639886", "yyyy-MM-dd HH:mm:ss");
返回值:2009-11-09 11:31:26
转自 http://blog.csdn.net/u013795673/article/details/50295679