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;
}