0

如何将纽约时区时间转换为“亚洲/加尔各答”日期和时间?

我的输入字符串:

11/28/2012 8:59am

我的代码:

String dtStart = "11/28/2012 8:59am";  
        SimpleDateFormat  format = new SimpleDateFormat("mm/dd/yyyy hh:mma");  
        format.setTimeZone(TimeZone.getTimeZone("America/New_York"));
        try {  
            Date date = format.parse(dtStart); 
            Log.i("clock", date.toString());
            System.out.println(date);


            Calendar cal = Calendar.getInstance();
            cal.setTimeInMillis(date.getTime());
            cal.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));
            int chour = cal.get(Calendar.HOUR_OF_DAY);
            int cminute = cal.get(Calendar.MINUTE);
            int dd = cal.get(Calendar.DAY_OF_MONTH);
            int mm =cal.get(Calendar.MONTH);
            int yy =cal.get(Calendar.YEAR);

            String mode="AM";

            if(chour>12)
            {
                chour=chour-12;
                mode="PM";
            }

            String mytime=Integer.toString(chour)+":"+Integer.toString(cminute)+" "+mode;
            String mydate=Integer.toString(dd)+"/"+Integer.toString(mm)+"/"+Integer.toString(yy);

            Log.i("clock", mytime);
            Log.i("clock", mydate);

        } catch (ParseException e) {  
            e.printStackTrace();  
        } catch (java.text.ParseException e) {
            e.printStackTrace();
        }

我的输出日志:

Sat Jan 28 19:29:00 GMT+05:30 2012
7:29 PM
28/0/2012

这里我的时间是正确的,但日期是错误的。我预计 2012 年 11 月 28 日。我无法追踪我做错了什么?

4

2 回答 2

4

问题在于您输入的格式:"mm/dd/yyyy hh:mma". 我相信你想这样做:"MM/dd/yyyy hh:mma"

于 2012-11-28T15:09:49.190 回答
0
SimpleDateFormat formatter = new SimpleDateFormat("MM/DD/YYYY hh:mm:ss a");
String dtStart = "11/28/2012 08:59 am";
Date dateObj = formatter.parse(dtStart); 
cal.setTime(dateObj);
fromTZObj = TimeZone.getTimeZone("America/New_York");
toTZObj = TimeZone.getTimeZone("Asia/Kolkata");
Calendar fromCal = new GregorianCalendar(fromTZObj);
fromCal.set(cal.get(1), cal.get(2), cal.get(5), cal.get(11), cal.get(12), 
cal.get(13));
Calendar toCal = new GregorianCalendar(toTZObj);
toCal.setTimeInMillis(fromCal.getTimeInMillis());
Date dd = toCal.getTime();
formatter.setTimeZone(toTZObj);
String formattedDate = format.format(dd);
System.out.println(formattedDate);
于 2021-01-08T17:44:43.043 回答