如何在android中将日期和时间转换为est格式?

这是我的代码。

public String getDateTime() { String dateAndTime = (new SimpleDateFormat("hh:mm aaa")).format(new Date()); return dateAndTime; } public String getDate() { android.text.format.DateFormat df = new android.text.format.DateFormat(); String Date = df.format("MM-dd-yyyy", new java.util.Date()).toString(); return Date; } 

我搜索过这个。 但是,我找不到完美的答案。 请帮帮我。

您可以使用以下function

  private Date shiftTimeZone(Date date, TimeZone sourceTimeZone, TimeZone targetTimeZone) { Calendar sourceCalendar = Calendar.getInstance(); sourceCalendar.setTime(date); sourceCalendar.setTimeZone(sourceTimeZone); Calendar targetCalendar = Calendar.getInstance(); for (int field : new int[] {Calendar.YEAR, Calendar.MONTH, Calendar.DAY_OF_MONTH, Calendar.HOUR, Calendar.MINUTE, Calendar.SECOND, Calendar.MILLISECOND}) { targetCalendar.set(field, sourceCalendar.get(field)); } targetCalendar.setTimeZone(targetTimeZone); System.out.println("........"+targetCalendar.getTimeZone()); return targetCalendar.getTime(); } 

用法:

  Date date= new Date(); SimpleDateFormat sf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); sf.format(date); TimeZone tz = TimeZone.getTimeZone("GMT") OR TimeZone tz = sf.getTimeZone(); TimeZone tz1 = TimeZone.getTimeZone("EST"); Date c= shiftTimeZone( date,tz,tz1); System.out.println("Format : " + sf.format(c)); 

输出sun.util.calendar.ZoneInfo [id =“EST”,offset = -18000000,dstSavings = 0,useDaylight = false,transitions = 0,lastRule = null]

  Format : 01-05-2013 16:23:57 

你可以在这里找到答案:

日期和时间转换为java中的其他时区

您必须使用TimeZone类和Calendar类。

获取当前时间:

 Calendar currentdatetime = Calendar.getInstance(); 

只需在TimeZone类中传递您的时区名称,如下所示:

 TimeZone.getTimeZone("EST"); 

使用DateFormater

 DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); 

然后像这样格式化你的时间:

 formatter.setTimeZone(obj); 

得到这样的输出:

 System.out.println("EST Time is : "+ formatter.format(currentdatetime .getTime())