kit*_*ttu 1 java timezone android simpledateformat
我遇到了一个问题:我想长时间获得GMT TimeZone的当前时间.我使用下面给出的代码:
TimeZone timeZoneGmt = TimeZone.getTimeZone("GMT");
long gmtCurrentTime = getCurrentTimeInSpecificTimeZone(timeZoneGmt);
public static long getCurrentTimeInSpecificTimeZone(TimeZone timeZone) {
Calendar cal = Calendar.getInstance();
cal.setTimeZone(timeZone);
long finalValue = 0;
SimpleDateFormat sdf = new SimpleDateFormat(
"MMM dd yyyy hh:mm:ss:SSSaaa");
sdf.setTimeZone(timeZone);
Date finalDate = null;
String date = sdf.format(cal.getTime());
try {
finalDate = sdf.parse(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finalValue = finalDate.getTime();
return finalValue;
}
Run Code Online (Sandbox Code Playgroud)
正如在上面的方法中给出的那样格式化
String date = sdf.format(cal.getTime());
我在GMT中获得正确的当前时间但是我通过以下代码进行解析:
finalDate=sdf.parse(date);
日期从当前GMT时间更改为2013年IST 2013年15:35:16,这是我系统的当前时间.
我尝试使用Calendar以另一种方式:
TimeZone timeZoneGmt=TimeZone.get("GMT");
Calendar calGmt = Calendar.getInstance();
calGmt.setTimeZone(timeZoneGmt);
long finalGmtValue = 0;
finalGmtValue = calGmt.getTimeInMillis();
System.out.println("Date......" + calGmt.getTime());
Run Code Online (Sandbox Code Playgroud)
但仍然得到我的系统的当前时间日期1月23日15:58:16 IST 2014没有获得GMT当前时间.
你误解了它是如何Date运作的.一个Date不具有时区-如果你使用Date.toString()你总是看到默认的时区.a中的long值Date纯粹是自Unix时代以来的毫秒数:它没有任何时区或日历系统的概念.
如果你想在特定的时区和日历中表示日期和时间,请Calendar改用 - 但是为了获得"当前日期和时间长",你可以使用System.currentTimeMillis(),这与系统时间无关区.
另外,即使您确实想要进行这样的操作,也不应该使用字符串转换.你在概念上没有执行任何字符串转换,为什么要介绍它们呢?
如果您的目标是在特定时区显示(作为字符串)当前日期和时间,您应该使用以下内容:
Date date = new Date(); // This will use the current time
SimpleDateFormat format = new SimpleDateFormat(...); // Pattern and locale
format.setTimeZone(zone); // The zone you want to display in
String formattedText = format.format(date);
Run Code Online (Sandbox Code Playgroud)
使用日期和时间API时 - 特别是像Java Calendar/ DateAPI 这样糟糕的API - 确切地了解系统中每个值所代表的内容非常重要.
| 归档时间: |
|
| 查看次数: |
1825 次 |
| 最近记录: |