如何在GM中将我的GMT时间转换为12小时格式的IST?

时间:2016-03-25 11:53:57

标签: android time

说明:            我有GMT格式的时间,我需要转换成IST。我已经做了但是24小时我想用AM / PM进行12小时格式化。

这是我的代码

DateFormat utcFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm'+00':ss");

utcFormat.setTimeZone(TimeZone.getTimeZone("IST"));
Date date1;
date1=utcFormat.parse(time);
Log.e("IST",""+date1.toString());//After convert in IST i got Sat Mar 26 19:30:00 GMT+05:30 2016

Date timestamp;
utcFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
timestamp = utcFormat.parse(time);
Log.e("timestamp", "" + timestamp.toString()); //After convert in UTC i got Sat Mar 26 19:30:00 GMT+05:30 2016
Log.e("Time",""+time.toString());//This is my time 2016-03-26T14:00+00:00

问题是IST和GMT同时出现问题。 我需要做什么,而不是在12小时内得到一段时间?

请帮我解决这个问题。

2 个答案:

答案 0 :(得分:0)

请记住,Date类不包含任何实际的时区信息,它只是UNIX纪元时间的long毫秒值。并且TimeZone的{​​{1}}仅在您显示日期时才相关,而不是在您解析日期时。因此,为了将SimpleDateFormat打印为IST日期,您必须在打印Date时使用该格式:

Date

对于12小时格式,您可以在打印时间时使用新的SimpleDateFormat进行设置。

// Parse your time string
DateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm'+00':ss");
Date date = myFormat.parse(time);

// Set a new format for displaying your time
DateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
isoFormat.setTimeZone(TimeZone.getTimeZone("IST"));

// This will print the IST time in the format specified: 2016-03-25T09:42:07+5:30
String istTime = isoFormat.format(date);
Log.d(istTime); 

Android还有一个有用的DateUtils课程,它会根据当前设备的设置格式化/** * 'hh' is the 12-hour time format, while 'HH' is the 24-hour format * 'hh' will always print two digits, while 'h' will drop leading zeros * 'a' is the AM/PM marker */ DateFormat dateFormat = new SimpleDateFormat("hh:mm a"); // This will print the current time, for example: 09:42 AM Log.d(dateFormat.format(new Date()));

答案 1 :(得分:0)

这里我创建了另一个DateFormat对象,并在其中传递一个参数'构造

//hh:mm a format of 12 hour with leading 0 before the hours, mm is for minutes and (a) is for AM/PM format.
//where as HH is provides the format of 24 hours.

这里我有12小时的格式。

DateFormat utcFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm'+00':ss");
utcFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
DateFormat outputFormat = new SimpleDateFormat("hh:mm a");

String ist=outputFormat.format(utcFormat.parse(time));
相关问题