Java实现的时间戳与date对象相互转换功能示例
本文实例讲述了Java实现的时间戳与date对象相互转换功能。分享给大家供大家参考,具体如下:
一.日期转换为时间戳
publiclonggetTimestamp()throwsParseException{
Datedate1=newSimpleDateFormat("yyyy/MM/ddHH:mm:ss")
.parse("2009/12/1100:00:00");
Datedate2=newSimpleDateFormat("yyyy/MM/ddHH:mm:ss")
.parse("1970/01/0108:00:00");
longl=date1.getTime()-date2.getTime()>0?date1.getTime()
-date2.getTime():date2.getTime()-date1.getTime();
longrand=(int)(Math.random()*1000);
returnrand;
}
二.时间戳转换为date型
publicvoidgetDate(StringunixDate){
SimpleDateFormatfm1=newSimpleDateFormat("dd/MM/yyyyHH:mm:ss");
SimpleDateFormatfm2=newSimpleDateFormat("yyyy-MM-ddhh:mm:ss");
longunixLong=0;
Stringdate="";
try{
unixLong=Long.parseLong(unixDate)*1000;
}catch(Exceptionex){
System.out.println("String转换Long错误,请确认数据可以转换!");
}
try{
date=fm1.format(unixLong);
date=fm2.format(newDate(date));
}catch(Exceptionex){
System.out.println("String转换Date错误,请确认数据可以转换!");
}
System.out.println(date);
}
系统获取时间戳:
System.currentTimeMillis();
PS:这里再为大家推荐几款时间及日期相关工具供大家参考使用:
Unix时间戳(timestamp)转换工具:
http://tools.jb51.net/code/unixtime
在线日期/天数计算器:
http://tools.jb51.net/jisuanqi/date_jisuanqi
在线日期计算器/相差天数计算器:
http://tools.jb51.net/jisuanqi/datecalc
在线日期天数差计算器:
http://tools.jb51.net/jisuanqi/onlinedatejsq
更多关于java相关内容感兴趣的读者可查看本站专题:《java日期与时间操作技巧汇总》、《Java数据结构与算法教程》、《Java操作DOM节点技巧总结》和《Java缓存操作技巧汇总》
希望本文所述对大家java程序设计有所帮助。