[英]Get date by utc/gmt in Android
I want to display the time in some Country, and the TimeZone is GMT+4. 我想在某个国家/地区显示时间,TimeZone是GMT + 4。
private void loadWeather(){
TimeZone tz = TimeZone.getTimeZone("GMT+0400");
Calendar cal = Calendar.getInstance(tz);
Date date = cal.getTime();
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT,DateFormat.SHORT, Locale.getDefault());
String myDate = df.format(date);
tv_time.setText(myDate);
}
I've tried this, but it gives me my time, and not the other one 我试过这个,但它给了我我的时间,而不是另一个
The problem is that you're specifying the time zone just on the Calendar
- which is only used to get the current instant in time, which doesn't depend on the time zone. 问题是你只是在
Calendar
上指定时区 - 它仅用于获取当前时刻,而不依赖于时区。 You need to specify it on the format instead, so that it's applied when creating an appropriate text representation of that instant: 您需要在格式上指定它,以便在创建该瞬间的适当文本表示时应用它:
private void loadWeather() {
Date date = new Date(); // This is enough; it uses the current instant.
DateFormat df = DateFormat.getDateTimeInstance(
DateFormat.SHORT, DateFormat.SHORT, Locale.getDefault());
df.setTimeZone(TimeZone.getTimeZone("GMT+0400"));
String myDate = df.format(date);
tv_time.setText(myDate);
}
Or to inline even more: 或者更内联:
private void loadWeather() {
DateFormat df = DateFormat.getDateTimeInstance(
DateFormat.SHORT, DateFormat.SHORT, Locale.getDefault());
df.setTimeZone(TimeZone.getTimeZone("GMT+0400"));
tv_time.setText(df.format(new Date()));
}
(This is assuming you really do want the short date/time format using the current locale.) (假设您确实需要使用当前区域设置的短日期/时间格式。)
Use SimpleDateFormat
as below and set the TimeZone
to the SimpleDateFormat
object...I think, you will get the problem right. 使用
SimpleDateFormat
下面,并设置TimeZone
为SimpleDateFormat
对象......我想,你会得到这个问题的权利。
Calendar calendar = Calendar.getInstance();
SimpleDateFormat dateFormatGmt = new SimpleDateFormat("dd:MM:yyyy HH:mm:ss");
dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT+0400"));
String date = dateFormatGmt.format(calendar.getTime());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.