0

I am using below method to display the time.

public static String getTimeByTimezone(String timeZone,Calendar localTime){     

        String time ="";
        Calendar indiaTime = new GregorianCalendar(TimeZone.getTimeZone(timeZone));
        indiaTime.setTimeInMillis(localTime.getTimeInMillis());
        int hour = indiaTime.get(Calendar.HOUR);
        int minute = indiaTime.get(Calendar.MINUTE);
        int second = indiaTime.get(Calendar.SECOND);
        int year = indiaTime.get(Calendar.YEAR);
//      /int am = indiaTime.get(Calendar.AM_PM);
        //System.out.printf("India time: %02d:%02d:%02d %02d\n", hour, minute, second, year);

        time = hour+":"+minute; 

        if(indiaTime.get(Calendar.AM_PM)==0)
            time=time+" AM";
        else
            time=time+" PM";
return time;
}

So what ever result is coming, if hour is less then 10 its appearing with single digits and same with the minutes, if minute is less then 10 its appearing with one digit. Ex: For Hour - > Getting: 9:15 AM Expected: 09:15 AM For Minute -> Getting: 9:8 AM Expected: 09:08 AM Can anybody tell me how to deal with digits.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Akash
  • 816
  • 3
  • 13
  • 38
  • 1
    Perhaps you should use a [`DateFormat`](http://docs.oracle.com/javase/7/docs/api/java/text/DateFormat.html). – khelwood Dec 19 '16 at 13:27
  • `08:00` is a `String`, `9:8` on the other hand are digits, (or do you write `08+09`?). For a `String` representation of the time use a `Formater` and the proper format you do want – SomeJavaGuy Dec 19 '16 at 13:27

1 Answers1

1

You could format your time String better :

time = String.format("%02d:%02d", 1, 5);   // = 01:05

However the way to go is to use a DateFormat :

SimpleDateFormat f = new SimpleDateFormat("hh:mm a");
f.format(indiaTime.getTime()); // = 01:05 PM
Aaron
  • 24,009
  • 2
  • 33
  • 57