gpt4 book ai didi

java - 根据当前位置/当前时区获取时间

转载 作者:搜寻专家 更新时间:2023-11-01 09:19:37 26 4
gpt4 key购买 nike

我想根据当前时区获取当前时间,即使我通过手机更改了当前时区并更改了我的时间,但我仍然应该能够获取当前时间和日期。如何获得?

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com