java日期和timestamp互相轉換

背景:java

在項目測試過程當中,須要用到long型的時間戳作測試。 所以須要將日期轉換爲long 型數據 (順帶把long 型數據轉換爲日期的功能一併研究了一下)。app

代碼以下:測試

1. 功能代碼:ui

 1 package com.wen.util.date;
 2 
 3 import java.text.ParseException;
 4 import java.text.SimpleDateFormat;
 5 import java.util.Date;
 6 
 7 public class Long_timer {
 8 
 9     // Get the long value of the current date
10     public long get_long_time()
11     {
12         Date mydate=new Date();        
13         return mydate.getTime();
14     }
15     
16     public long date2long(String year,String month,String day,String hour,String minutes,String sec,String sss)
17     {
18         StringBuilder sb=new StringBuilder();
19         sb.append(month);
20         sb.append("/");
21         sb.append(day);
22         sb.append("/");
23         sb.append(year);
24         sb.append(" ");
25         sb.append(hour);
26         sb.append(":");
27         sb.append(minutes);
28         sb.append(":");
29         sb.append(sec);
30         sb.append(".");
31         sb.append(sss);
32         
33         String sDt = sb.toString();
34 
35         SimpleDateFormat sdf=new SimpleDateFormat("MM/dd/yyyy HH:mm:ss.SSS");
36         Date dt = null;
37         try {
38             dt = sdf.parse(sDt);
39             
40         } catch (ParseException e) {
41             // TODO Auto-generated catch block
42             e.printStackTrace();
43         }
44         
45         return dt.getTime();
46     }
47 
48     public Date long2date(long timestamp)
49     {
50         Date mydate=new Date();
51         mydate.setTime(timestamp);
52         return mydate;
53     }
54 }

2. 測試代碼:spa

package com.wen.util.date;

public class TestClient {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        long t=System.currentTimeMillis();
    
        Long_timer test= new Long_timer();
        System.out.println("current time is: "+t);        
        System.out.println("the long time of now: "+test.get_long_time());
        System.out.println("the long time for specified date:"+test.date2long("2017","04","10","17","41","53","819"));
    }
}
相關文章
相關標籤/搜索