1. 程式人生 > >時間戳和時間的相互轉換

時間戳和時間的相互轉換

時間戳和時間相互轉換測試:

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class StampAndDate {

	
	    public static void main(String[] args)
	    {
	        // TODO Auto-generated method stub
	        if (args.length < 1)
	        {
	            return;
	        }
	        //輸入檔名來連線檔案
	        File file = new File(args[0]);
	        
	        System.out.println("最後修改時間(時間戳):" + file.lastModified());
	        System.out.println("最後修改時間(時間):"+stampToDate(String.valueOf(file.lastModified())));
	        try {
				System.out.println("最後修改時間(時間戳):" +dateToStamp(stampToDate(String.valueOf(file.lastModified()))));
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	    }
	    
	    /* 
         * 將時間轉換為時間戳
         */    
        public static String dateToStamp(String s) throws ParseException{
            String res;
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
            Date date = (Date) simpleDateFormat.parse(s);
            long ts = date.getTime();
            res = String.valueOf(ts);
            return res;
        }
        /* 
         * 將時間戳轉換為時間
         */
        public static String stampToDate(String s){
            String res;
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
            long lt = new Long(s);
            Date date = new Date(lt);
            res = simpleDateFormat.format(date);
            return res;
        }
	}
結果: 引數:1.txt        1.txt要先實現建立好