Android 时间戳的转换

  在Android应用中,经常会碰到后台的时间是时间戳而现实的需要今天什么时候,昨天什么时候,就像微博的时间显示一样。现在我上一个把时间戳转换的代码:

  public static String getTime(int timestamp) {
  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  String time = null;
  try {
   java.util.Date currentdate = new java.util.Date();// 当前时间

   long i = (currentdate.getTime() / 1000 - timestamp) / (60);
   Timestamp now = new Timestamp(System.currentTimeMillis());// 获取系统当前时间
   String str = sdf.format(new Timestamp(IntToLong(timestamp)));
   time = str.substring(11, 16);
   String year = str.substring(0, 4);
   String month = str.substring(5, 7);
   String day = str.substring(8, 10);
   System.out.println(str);
   System.out.println(time);
   System.out.println(getDate(year, month, day));
   time = getDate(year, month, day) + time;
  } catch (Exception e) {
   e.printStackTrace();
  }
  return time;
 }

 // java Timestamp构造函数需传入Long型
 public static long IntToLong(int i) {
  long result = (long) i;
  result *= 1000;
  return result;
 }

 public static String getDate(final String year, final String month,
   final String day) {
  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 24小时制
  java.util.Date d = new java.util.Date();
  String str = sdf.format(d);
  String nowmonth = str.substring(5, 7);
  String nowday = str.substring(8, 10);
  String result = null;

  int temp = Integer.parseInt(nowday) - Integer.parseInt(day);
  switch (temp) {
  case 0:
   result = "今天";
   break;
  case 1:
   result = "昨天";
   break;
  case 2:
   result = "前天";
   break;
  default:
   StringBuilder sb = new StringBuilder();
   sb.append(year).append("-");
   sb.append(month).append("-");
   sb.append(day).append(" ");
   result = sb.toString();
   break;
  }
  return result;
 }

你可能感兴趣的:(Android)