/**
* @author HuWT
*/
public class TimeTool {
private static final String TAG = "TimeTool";
// 从淘宝网获取时间
private static final String TIME_URL = "http://www.taobao.com";
private static Date date;
/**
* 将 TimeTool.date表示的时间加上 minutes分钟
* @param minutes
* @return 通过 getStrDate()返回一个可以被Shell命令解析的日期字符串
*/
public static String getLocalTimeAdd(long minutes){
if (TimeTool.date == null){
Log.i(TAG, "getLocalTimeAdd: \n***** 请在使用本方法前,确保TimeTool.date != null");
return null;
}
long ms = minutes * 60 * 1000;
// 下行中的date可以换成 System.currentTimeMillis() 来确保Time.date != null
/* 这里使用 TimeTool.date 是项目要求的.所以, 准确的来说,
* 本方法是对最近获取的网络时间进行加减
*/
long newMS = (Long.valueOf(date.getTime())+ms);
return getStrDate(new Date(newMS));
}
/**
* 获取最新的网络时间, 并将时间保存到 TimeTool.date
* @return
*/
public static String getNetDate() {
// 更新 TimeTool.date
getDatefrom();
Date temp = TimeTool.date;
while (TimeTool.date == temp) {
sleep(500);
Log.d(TAG, "getNetDate: 正在等待TimeTool.date更新...");
}
return getStrDate(TimeTool.date);
}
/**
* 从网络上获取时间, 并将时间保存到 TimeTool.date
*/
private static void getDatefrom() {
new Thread() {
@Override
public void run() {
URL url = null;
try {
url = new URL(TIME_URL);
} catch (MalformedURLException e) {
e.printStackTrace();
}
//生成连接对象
URLConnection uc = null;
try {
uc = url.openConnection();
//发出连接
uc.connect();
} catch (IOException e) {
e.printStackTrace();
}
//取得网站日期时间
long ld = uc.getDate();
//转换为标准时间对象
TimeTool.date = new Date(ld);
}
}.start();
}
/**
* 将 Date 类型转换为 Shell date -s命令可以使用的 字符型格式
* @param date
* @return
*/
static String getStrDate(Date date){
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd.HHmmss");
return sdf.format(date);
}
}