本文實(shí)例講述了Java實(shí)現(xiàn)的時(shí)間戳與date對(duì)象相互轉(zhuǎn)換功能。分享給大家供大家參考,具體如下:
一.日期轉(zhuǎn)換為時(shí)間戳
1
2
3
4
5
6
7
8
9
10
|
public long getTimestamp() throws ParseException{ Date date1 = new SimpleDateFormat( "yyyy/MM/dd HH:mm:ss" ) .parse( "2009/12/11 00:00:00" ); Date date2 = new SimpleDateFormat( "yyyy/MM/dd HH:mm:ss" ) .parse( "1970/01/01 08:00:00" ); long l = date1.getTime() - date2.getTime() > 0 ? date1.getTime() - date2.getTime() : date2.getTime() - date1.getTime(); long rand = ( int )(Math.random()* 1000 ); return rand; } |
二.時(shí)間戳轉(zhuǎn)換為date 型
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
public void getDate(String unixDate) { SimpleDateFormat fm1 = new SimpleDateFormat( "dd/MM/yyyy HH:mm:ss" ); SimpleDateFormat fm2 = new SimpleDateFormat( "yyyy-MM-dd hh:mm:ss" ); long unixLong = 0 ; String date = "" ; try { unixLong = Long.parseLong(unixDate) * 1000 ; } catch (Exception ex) { System.out.println( "String轉(zhuǎn)換Long錯(cuò)誤,請(qǐng)確認(rèn)數(shù)據(jù)可以轉(zhuǎn)換!" ); } try { date = fm1.format(unixLong); date = fm2.format( new Date(date)); } catch (Exception ex) { System.out.println( "String轉(zhuǎn)換Date錯(cuò)誤,請(qǐng)確認(rèn)數(shù)據(jù)可以轉(zhuǎn)換!" ); } System.out.println(date); } |
系統(tǒng)獲取時(shí)間戳 :
1
|
System.currentTimeMillis(); |
希望本文所述對(duì)大家java程序設(shè)計(jì)有所幫助。