如何转换日期和时间共青格式的Andr​​oid?日期、格式、时间、共青

2023-09-05 01:08:40 作者:The silence 沉默

下面是我的code。

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;
}

我寻觅这个问题。但是,我不能找到完美的答案。请帮我。

I have searched about this. but, i cant find the perfect answer. Please help me.

推荐答案

您可以使用下面的函数

    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]

Output sun.util.calendar.ZoneInfo[id="EST",offset=-18000000,dstSavings=0,useDaylight=false,transitions=0,lastRule=null]

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