How to get hours and minutes from a String variable ?

17,618

Solution 1

Try this way, by split() method,

String timme = "13:10";
String[] time = timme.split ( ":" );
int hour = Integer.parseInt ( time[0].trim() );
int min = Integer.parseInt ( time[1].trim() );

Solution 2

Better use Date and DateFormat:

String time = "13:10";

DateFormat sdf = new SimpleDateFormat("HH:mm"); // or "hh:mm" for 12 hour format
Date date = sdf.parse(time);

date.getHours(); // int
date.getMinutes(); // int

Solution 3

You could use Calendar object of java instead of Date object,

SimpleDateFormat dateFormatter = new SimpleDateFormat("HH:mm", Locale.ENGLISH);
        try {
            Calendar c = Calendar.getInstance();
            c.setTime(dateFormatter.parse("07:30"));
            String hour = String.valueOf(c.get(Calendar.HOUR_OF_DAY));
            String mintue = String.valueOf(c.get(Calendar.MINUTE));
            System.out.println("Hour: " + hour);
            System.out.println("Minute: " + mintue);
        } catch (ParseException e) {
            e.printStackTrace();
        }

Solution 4

You can try this...

String time = "13:10";
SimpleDateFormat formatter =  = new SimpleDateFormat("hh:mm");
Date dTime = formatter.parse(time);
int hour = dTime.getHours();
int minute = dTime.getMinutes();
Share:
17,618
user2219097
Author by

user2219097

Updated on June 05, 2022

Comments

  • user2219097
    user2219097 almost 2 years

    I have a String timme = "13:10". I was wondering how would I best go about getting the hours and minutes and converting them into integers. i.e. int hours = 13 , int minute = 10. I know a for-loop wouldn't be the most efficient way, is there anything simpler?

  • user3317558
    user3317558 over 10 years
    how about if time = "9:10" ? or time = "10:9" ?
  • Sahil Mahajan Mj
    Sahil Mahajan Mj over 10 years
    what if the time = "6:10"?
  • user3317558
    user3317558 over 10 years
    @user2219097 , you can appreciate by accepting my answer :)
  • Sahil Mahajan Mj
    Sahil Mahajan Mj over 10 years
    +1, same approach I was thinking. but why you have used trim()?
  • user3317558
    user3317558 over 10 years
    @SahilMahajanMj, It is security step to avoid any white space.
  • Sahil Mahajan Mj
    Sahil Mahajan Mj over 10 years
    @user3317558: you are really doing well in SO. Happy to see your eagerness to answer in the very first day of joining.
  • user3317558
    user3317558 over 10 years
    @SahilMahajanMj Thank you Sir.