一、原理
时间戳的原理是把时间格式转为十进制格式,这样就方便时间的计算。好~ 直接进入主题。(下面封装了一个类,有需要的同学可以参考或是直接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("时间格式");//时间格式转为时间戳