0

I am using the SimpleDateFormat to get the time in a format. When I do that I get the format in a String variable. I wonder if there is a built in method to get the hour and the minute from the string variable separatly?

SimpleDateFormat sdf = new SimpleDateFormat("hh:mm a");   
String time = sdf.format(calendar.getTime());

Lets say my string get this format: 12:34 AM

I want to separate the hour and the minute. I want 12 and 34 in a new variable.

I don't want to use this:

  int hour = calendar.get(Calendar.HOUR_OF_DAY);

Because I only have access to the string variable when I save it in SharedPreferences.

EM10
  • 795
  • 7
  • 12
  • 24

4 Answers4

1

You can get it from the calendar object

int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
Will
  • 6,179
  • 4
  • 31
  • 49
  • Because I use the string variable somewhere else in the program I can't use the calendar object. – EM10 Mar 30 '14 at 18:15
  • 1
    @EM10, Convert it back to a DateTime then. Leaving it as a string doesn't help you anyway, you'd have to know the format to chops parts out of it, which would make your code extremely fragile. Tip for dealing with dates, is converting from a string is the first thing you do, converting to string the last. Anything else is a bug fest. – Tony Hopkinson Mar 30 '14 at 18:24
1

could you write us what is the "time" that you get back? I think, with string manipulation you can solve this problem.

mig8
  • 122
  • 4
1

You can get a java.util.Date object from your String, it is explained here: Java string to date conversion

public static final String YOUR_FORMAT = "hh:mm a";

Date yourDateTime = new SimpleDateFormat(YOUR_FORMAT).parse(time);

Calendar cal = Calendar.getInstance();
cal.setTime(yourDateTime);
int hour = cal.get(Calendar.HOUR_OF_DAY);

Other way is split the String:

int hour = Integer.parseInt(time.split("\\:")[0]);
Community
  • 1
  • 1
carlosvin
  • 979
  • 9
  • 22
1

I would convert it back to Date with same format you've used to get this String. Any String manipulations will be fragile. You should hold your format String in one place, so whenever you change it, your code will still work as it should.

    //Get this one provided by dependency injection for example
    SimpleDateFormat sdf = new SimpleDateFormat("hh:mm a");
    String dateString = sdf.format(new Date());
    Date date = sdf.parse(dateString);
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);

    int hour = calendar.get(Calendar.HOUR_OF_DAY);
    int minute = calendar.get(Calendar.MINUTE);
enterbios
  • 1,725
  • 12
  • 13