Pergunta

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.

Foi útil?

Solução

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

Outras dicas

You can get it from the calendar object

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

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

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]);
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top