Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,895 questions

51,826 answers

573 users

How to extract hours, minutes and second from string in Java

2 Answers

0 votes
import java.util.ArrayList;

public class MyClass {
    public static void main(String args[]) {
        String str = "11:58:35";

	    ArrayList<String> time_parts = new ArrayList<String>();
	    int pos = 0;

	    while ((pos = str.indexOf(":", pos)) != -1) {
		    time_parts.add(str.substring(0, pos));
		    str = str.substring(pos + 1);
	    }
	    time_parts.add(str); // Add the seconds

    	if (time_parts.size() != 3) {
		    System.out.println("Invalid time format");
	    }

	    int hours = Integer.parseInt(time_parts.get(0));
	    int minutes = Integer.parseInt(time_parts.get(1));
	    int seconds = Integer.parseInt(time_parts.get(2));

	    System.out.println(hours + ":" + minutes + ":" + seconds);
    }
}







/*
run:
 
11:58:35
 
*/

 



answered Dec 27, 2023 by avibootz
edited Dec 27, 2023 by avibootz
0 votes
import java.util.ArrayList;
 
public class MyClass {
    public static void main(String args[]) {
        String str = "11:58:35";
 
        String[] arr = str.split ( ":" );
        
        int hours = Integer.parseInt(arr[0].trim());
        int minutes = Integer.parseInt(arr[1].trim());
        int seconds = Integer.parseInt(arr[2].trim());
 
        System.out.println(hours + ":" + minutes + ":" + seconds);
    }
}
 
 
  
 
 
/*
run:
  
11:58:35
  
*/

 



answered Dec 28, 2023 by avibootz

Related questions

1 answer 140 views
1 answer 104 views
2 answers 152 views
2 answers 161 views
2 answers 108 views
...