我想根据当前时区获取当前时间,即使我从手机更改当前时区并更改时间,但我仍然应该能够获取当前时间和日期。如何得到它?
Time currentTime = new Time();
currentTime.setToNow();
Calendar cal = Calendar.getInstance();
TimeZone tz = cal.getTimeZone();
Date date = cal.getTime();
strDate = date.toString();
最佳答案
使用该方法获取本地时间
public static Date getLocalDate(String timeStamp) {
int index = timeStamp.indexOf("+");
String dateTime;
if (index > 0) {
timeStamp = timeStamp.substring(0, index);
}
int indexGMT = timeStamp.indexOf("GMT");
int indexPlus = timeStamp.indexOf("+");
if (indexGMT > 0) {
dateTime = timeStamp.substring(0, indexGMT);
} else if (indexPlus > 0) {
dateTime = timeStamp.substring(0, indexPlus);
} else {
dateTime = timeStamp;
}
SimpleDateFormat sdfgmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdfgmt.setTimeZone(TimeZone.getTimeZone("GMT"));
SimpleDateFormat sdfmad = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdfmad.setTimeZone(TimeZone.getDefault());
Date gmtDate;
Date localDate = null;
try {
gmtDate = sdfgmt.parse(dateTime);
localDate = sdfmad.parse(sdfmad.format(gmtDate));
} catch (ParseException e) {
}
return localDate;
}
要获取当前的 UNIX 时间戳,可以使用以下代码
long unixTime = System.currentTimeMillis() / 1000L;
关于java - 根据当前位置/当前时区获取时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57393462/