如何在Android中将当前日期时间从IST转换为EST时区?
如何将EST时区日期(已转换并获取字符串)转换为带有时区的日期格式? 我尝试更改时区,得到了字符串格式的完美日期时间,但当我将字符串日期解析为日期格式时,它给了我本地Android系统时区时间。如何在Android中将当前日期时间从IST转换为EST时区?,android,date,timezone,Android,Date,Timezone,如何将EST时区日期(已转换并获取字符串)转换为带有时区的日期格式? 我尝试更改时区,得到了字符串格式的完美日期时间,但当我将字符串日期解析为日期格式时,它给了我本地Android系统时区时间。 提前谢谢你的帮助 DateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm aa"); TimeZone tz = TimeZone.getTimeZone("EST"); outputFormat.setTimeZone(tz);
提前谢谢你的帮助
DateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm aa");
TimeZone tz = TimeZone.getTimeZone("EST");
outputFormat.setTimeZone(tz);
String current_date = outputFormat.format(date);
Date currentdate = outputFormat.parse(current_date);
它以字符串形式给出最新的日期格式(当前日期)。
它给出了一个列表格式日期(currentdate)您实际上是将字符串的输出返回到其原始时区,因此,当您格式化从
IST
到EST
的日期时,它将为您提供正确的指定时区,但当您parse
时,它将还原回手机当前使用的时区
解决方案:
Date date = new Date();
SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm aa");
TimeZone tz = TimeZone.getTimeZone("IST");
outputFormat.setTimeZone(tz);
String current_date = outputFormat.format(date);
SimpleDateFormat outputFormat2 = new SimpleDateFormat("yyyy-MM-dd hh:mm aa");
Date currentdate = outputFormat2.parse(current_date);
使用另一个SimpleDataFormat
实例,并使用该实例来解析该字符串,以防止该字符串还原回其当前时区
示例:
Date date = new Date();
SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm aa");
TimeZone tz = TimeZone.getTimeZone("IST");
outputFormat.setTimeZone(tz);
String current_date = outputFormat.format(date);
SimpleDateFormat outputFormat2 = new SimpleDateFormat("yyyy-MM-dd hh:mm aa");
Date currentdate = outputFormat2.parse(current_date);
@KDOSHI它会给你IST,但时间本身是EST你是对的,但它给我这样的时间:8月9日星期六01:44:00 GMT+2014年5:30如果我想比较这两个日期,比如If(expirydate.compareTo(currentdate)>0,那么它是否有效!我认为您不能更改日期的toString格式,相反,您可以操作字符串,因此不必比较日期,使用字符串比较的replace
方法比较字符串并将GMT替换为EST在日期比较的情况下字符串比较不是有效的解决方案。@KDOSHI无法更改日期的时区,因为它使用的是设备的默认时区getDefault
。您需要使用。如果EST指的是北美东部时间,请使用“America/NewYork”
。如果IST指的是印度标准时间,请使用“亚洲/加尔各答”
。