zoukankan      html  css  js  c++  java
  • java日期和timestamp互相转换

    背景:

    在项目测试过程中,需要用到long型的时间戳做测试。 因此需要将日期转换为long 型数据 (顺带把long 型数据转换为日期的功能一并研究了一下)。

    代码如下:

    1. 功能代码:

     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. 测试代码:

    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"));
        }
    }



  • 相关阅读:
    跳出iframe
    leetcode 225. Implement Stack using Queues
    leetcode 206. Reverse Linked List
    leetcode 205. Isomorphic Strings
    leetcode 203. Remove Linked List Elements
    leetcode 198. House Robber
    leetcode 190. Reverse Bits
    leetcode leetcode 783. Minimum Distance Between BST Nodes
    leetcode 202. Happy Number
    leetcode 389. Find the Difference
  • 原文地址:https://www.cnblogs.com/wenchunl/p/6825610.html
Copyright © 2011-2022 走看看