package com.example.currenttime;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class Functions {
private static long converTimeStringINToMillis1(String time) {
long milliseconds = 0;
try {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
// 25/06/2014 8:41:26
Date date;
date = sdf.parse(time);
milliseconds = date.getTime();
} catch (ParseException e) {
// TODO Auto-generated catch block
milliseconds = 0;
e.printStackTrace();
}
return milliseconds;
}
public static String setLastSeenTime1(String time) {
long milliseconds = Math.abs(System.currentTimeMillis()
- converTimeStringINToMillis1(time));
String lastSeen = "";
int seconds = (int) milliseconds / 1000;
if (seconds < 60)
lastSeen = String.valueOf(seconds) + "sec ago";
else if (seconds > 60 && seconds < 3600)
lastSeen = String.valueOf((int) seconds / 60) + " min ago";
else if (seconds > 3600 && seconds < 86400)
lastSeen = String.valueOf((int) seconds / 3600) + " hours ago";
else if (seconds > 86400 && seconds < 172800)
lastSeen = " Yesterday";
else if (seconds > 172800 && seconds < 2592000)
lastSeen = String.valueOf((int) (seconds / (24 * 3600)))
+ " days ago";
else if (seconds > 2592000)
lastSeen = String.valueOf((int) (seconds / (30 * 24 * 3600)))
+ " months ago";
return lastSeen;
}
}
我有显示反向时间我调用这个函数使用这个android代码:
btn_retry.setText(Functions.setLastSeenTime1("09/10/2014 8:41:26 AM"))
但问题是我正在获取位于美国的服务器时间,我必须根据本地时区显示,以便我可以看到弹出时间,请建议我如何做,哪里做错了,请帮助。
最佳答案
更新: 这应该可行,只需在实用程序类中替换它,您只需传递时间和 serverTimeZone 即可。
public static String setLastSeenTime1(String time, TimeZone serverTimeZone) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");
sdf.setTimeZone(serverTimeZone);
SimpleDateFormat sdf2 = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");
sdf.setTimeZone(TimeZone.getDefault());
return sdf2.format(sdf.parse(time));
}
关于java - 如何从美国时间获取android中的反向时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26277193/