一、原理
時間戳記的原理是把時間格式轉為十進位格式,這樣就方便時間的計算。好~ 直接進入主題。(下面封裝了一個類,有需要的同學可以參考或是直接Copy 就可以用了。)
如: 2013年08月23日 轉化後是 1377216000000
二、步驟
1、建立 DateUtilsl類。
| 代碼如下 |
複製代碼 |
importjava.text.ParseException; importjava.text.SimpleDateFormat; importjava.util.Date; /* * @author Msquirrel */ public class DateUtils { privateSimpleDateFormat sf = null; /*擷取系統時間 格式為:"yyyy/MM/dd "*/ public static String getCurrentDate() { Date d = newDate(); sf = newSimpleDateFormat("yyyy年MM月dd日"); returnsf.format(d); } /*時間戳記轉換成字元竄*/ public static String getDateToString(long time) { Date d = newDate(time); sf = newSimpleDateFormat("yyyy年MM月dd日"); returnsf.format(d); } /*將字串轉為時間戳記*/ public static long getStringToDate(String time) { sdf = newSimpleDateFormat("yyyy年MM月dd日"); Date date = newDate(); try{ date = sdf.parse(time); } catch(ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } returndate.getTime(); }
|
2、在對應使用的地方調用就可以了。
| 代碼如下 |
複製代碼 |
DateUtils.getCurrentDate(); //擷取系統目前時間 DateUtils.getDateToString(時間戳記); //時間戳記轉為時間格式 DateUtils.getStringToDate("時間格式");//時間格式轉為時間戳記
|