[英]Convert UTC into Local Time on Android
In my project, I have get the API response in json format.在我的项目中,我得到了 json 格式的 API 响应。 I get a string value of time in UTC time format like this
Jul 16, 2013 12:08:59 AM
.我得到一个 UTC 时间格式的时间字符串值,例如
Jul 16, 2013 12:08:59 AM
。
I need to change this into Local time.我需要将其更改为当地时间。 That is where ever we use this the app needs to show the local time.
那就是我们使用这个应用程序需要显示当地时间的地方。 How to I do this?
我该怎么做?
Here is some Code I have tried:这是我尝试过的一些代码:
String aDate = getValue("dateTime", aEventJson);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM dd, yyyy HH:mm:ss z");
simpleDateFormat.setTimeZone(TimeZone.getDefault());
String formattedDate = simpleDateFormat.format(aDate);
Assume aDate contains Jul 16, 2013 12:08:59 AM
假设 aDate 包含
Jul 16, 2013 12:08:59 AM
Here's my attempt:这是我的尝试:
String dateStr = "Jul 16, 2013 12:08:59 AM";
SimpleDateFormat df = new SimpleDateFormat("MMM dd, yyyy HH:mm:ss a", Locale.ENGLISH);
df.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = df.parse(dateStr);
df.setTimeZone(TimeZone.getDefault());
String formattedDate = df.format(date);
Also notice the "a" for the am/pm marker...还要注意上午/下午标记的“a”...
I should like to contribute the modern answer.我想贡献现代答案。 While
SimpleDateFormat
was the class we had for parsing and formatting date-times in 2013 (apart from Joda-Time), it is now long outdated, and we have so much better in java.time
or JSR-310, the modern Java date and time API that came out with Java 8 in 2014.虽然
SimpleDateFormat
是我们在 2013 年用于解析和格式化日期时间的类(除了 Joda-Time),但它现在已经过时了,而且我们在java.time
或 JSR-310(现代 Java 日期和2014 年随 Java 8 发布的 time API。
But most Android devices still don't run Java 8, I hear you say.但我听到你说,大多数 Android 设备仍然不运行 Java 8。 Fortunately you can still use the modern Java date and time API on them through the ThreeTenABP, the backport of JSR-310 to Android Java 7. Details are in this question: How to use ThreeTenABP in Android Project .
幸运的是,您仍然可以通过 ThreeTenABP(JSR-310 到 Android Java 7 的反向移植)在它们上使用现代 Java 日期和时间 API。详细信息在这个问题中:如何在 Android 项目中使用 ThreeTenABP 。
Now the code is:现在代码是:
DateTimeFormatter formatter
= DateTimeFormatter.ofPattern("MMM dd, uuuu hh:mm:ss a", Locale.ENGLISH);
String aDate = "Jul 16, 2013 12:08:59 AM";
String formattedDate = LocalDateTime.parse(aDate, formatter)
.atOffset(ZoneOffset.UTC)
.atZoneSameInstant(ZoneId.systemDefault())
.format(formatter);
System.out.println(formattedDate);
Since my computer is running Europe/Copenhagen time zone, which in July is 2 hours ahead of UTC, this prints由于我的计算机运行的是欧洲/哥本哈根时区,在 7 月比 UTC 早 2 小时,因此打印
Jul 16, 2013 02:08:59 AM
Further points:进一步的要点:
h
in the format pattern string.h
。 Uppercase H
is for hour-of-day from 0 through 23.H
表示从 0 到 23 的时间。SimpleDateFormat
or DateTimeFormatter
).SimpleDateFormat
还是DateTimeFormatter
)。 If no locale is given, the formatter will use the device's default locale.ZoneId.of("Asia/Kolkata")
.ZoneId.of("Asia/Kolkata")
。 The JVM's default time zone may be changed by other parts of your program or other programs running in the same JVM, so is not reliable. 1.Local to UTC Converter 1.本地到UTC转换器
public static String localToUTC(String dateFormat, String datesToConvert) {
String dateToReturn = datesToConvert;
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
sdf.setTimeZone(TimeZone.getDefault());
Date gmt = null;
SimpleDateFormat sdfOutPutToSend = new SimpleDateFormat(dateFormat);
sdfOutPutToSend.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
gmt = sdf.parse(datesToConvert);
dateToReturn = sdfOutPutToSend.format(gmt);
} catch (ParseException e) {
e.printStackTrace();
}
return dateToReturn;
}
2. UTC to Local Converter 2. UTC 到本地转换器
public static String uTCToLocal(String dateFormatInPut, String dateFomratOutPut, String datesToConvert) {
String dateToReturn = datesToConvert;
SimpleDateFormat sdf = new SimpleDateFormat(dateFormatInPut);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date gmt = null;
SimpleDateFormat sdfOutPutToSend = new SimpleDateFormat(dateFomratOutPut);
sdfOutPutToSend.setTimeZone(TimeZone.getDefault());
try {
gmt = sdf.parse(datesToConvert);
dateToReturn = sdfOutPutToSend.format(gmt);
} catch (ParseException e) {
e.printStackTrace();
}
return dateToReturn; }
//your UTC time var
long time = UTCtime;
//convert it
Time timeFormat = new Time();
timeFormat.set(time+TimeZone.getDefault().getOffset(time));
//use the value
long localTime = timeFormat.toMillis(true);
Use the following code.使用以下代码。
TimeZone defaultTimeZone = TimeZone.getDefault();
String strDefaultTimeZone = defaultTimeZone.getDisplayName(false, TimeZone.SHORT);
//The code you use
String aDate = getValue("dateTime", aEventJson);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM dd, yyyy HH:mm:ss z");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone(strDefaultTimeZone));
String formattedDate = simpleDateFormat.format(aDate);
This should work.这应该有效。
This is how i do it on android Build.VERSION.SDK_INT < 26这就是我在 android Build.VERSION.SDK_INT < 26 上的做法
int offset = TimeZone.getDefault().getRawOffset();
String str_date='20:30 12-01-2021';
DateFormat formatter = new SimpleDateFormat("HH:mm dd-MM-yyy",Locale.US);
Date date = formatter.parse(str_date);
long utcTime = date.getTime() + (3600000*3);
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm dd/MM/yyyy", Locale.US);
String dateStr = sdf.format(utcTime + offset);
System.out.println(dateStr);
As my server sends the time with -3 timezone i have to add (3600*3) to getTime and i save it into utcTime, this way utcTime is in UTC.当我的服务器使用 -3 时区发送时间时,我必须将 (3600*3) 添加到 getTime 并将其保存到 utcTime,这样 utcTime 就是 UTC。 And then i add to utcTime the offset of the phone current timezone.
然后我将手机当前时区的偏移量添加到 utcTime。 In my case as my timezone is -3 its prints:
在我的情况下,因为我的时区是 -3 它的打印:
20:30 12/01/2021
But if i change my time zone the date also changes.但如果我改变我的时区,日期也会改变。
Use this code:使用此代码:
public static String stringDateWithTimezone(Date date, String pattern, TimeZone timeZone) {
try {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern, Locale.US);
if (timeZone != null) {
simpleDateFormat.setTimeZone(timeZone);
}
return simpleDateFormat.format(date);
} catch (Exception e) {
Timber.e(e);
return null;
}
}
call in another class:调用另一个类:
String dateUtc = DateUtil.stringDateWithTimezone(new Date(), "yyyy-MM-dd hh:mm:ss", TimeZone.getTimeZone("UTC"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.