Date、String和Timestamp类型转换

闲来无事,就做了一下技术总结,可能网上关于date与String类型的转换到处都是,我也承认,写这边类型转换之前也有看过那些文档,但是都几乎千遍一律,同时我觉得自我重新总结一遍,会有很大帮助,因此写下该日期处理总结:

1StringDate类型转换:

1、获取当前系统时间:

Date date1 new Date();   //获取系统当前时间

Calendar cal Calendar.getInstance();

Date cal.getTime();  //获取系统当前时间

System.currentTimeMillis(); //获取系统当前时间毫秒数

2Date类型转换为String类型:

SimpleDateFormat sdf new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");

SimpleDateFormat sdf1 new SimpleDateFormat("yyyyMMdd");

String str sdf.format(date1);

String str1 =sdf1.format(date1); 

System.out.println(str);

System.out.println(str1);  

说明:sdfsdf1只是两个不懂的格式化类型的定义,类型可以自由定义。

效果如下:

   3String类型转换为Date类型:

String str2 "2011-02-02 12:12:12";

SimpleDateFormat sdf2 new SimpleDateFormat("yyyy-MM-dd");

SimpleDateFormat sdf3 new SimpleDateFormat

("yyyy-MM-dd HH:mm:ss");

Date date3 sdf2.parse(str2);

Date date4 sdf3.parse(str2);

System.out.println(date3);

System.out.println(date4);


说明:sdf2sdf3的格式要求,区别是时间部分,另不可在格式化中出现中文字符。

String str4 "2012-01-04";

//只显示日期部分

System.out.println(java.sql.Date.valueOf(str4));

   

由于Date类型只能显示时间部分,而无法显示时间不分,因而出现了timestamp类型。

2StringTimestamp类型转换:

1String转换为Timestamp类型:

String str3 "2011-02-02 12:12:12";

Timestamp.valueOf(str3);

System.out.println(Timestamp.valueOf(str3));


  2timestamp转换为string类型

Long System.currentTimeMillis();

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

System.out.println(Timestamp.valueOf(format.format(l)));


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值