android小知识——时间与时间戳之间的转化

来源:互联网 发布:淘宝店铺首页大图 编辑:程序博客网 时间:2024/06/06 20:16
时间戳就是如1377216000000 这种格式我们在mysql数据库中会经常用到把时间转换成时间戳或把时间戳转换成日期格式了,下面我来介绍安卓中时间戳操作转换方法。
  一、原理
  时间戳的原理是把时间格式转为十进制格式,这样就方便时间的计算。好~ 直接进入主题。(下面封装了一个类,有需要的同学可以参考或是直接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("时间格式");//时间格式转为时间戳
0 0