how-to

Conversion between types

How to convert string to time

For this example you need to use:

import java.text.*;

For conversion is used SimpleDateFormat class, that specifies used date mask.

/* - value for conversion */
    
String s = "13:52:10";
    
/* - specify format mask */
   
DateFormat df = new SimpleDateFormat( "H:m:s" );
    
try {
  /* - try to convert */
      
  Date d = df.parse( s );              
      
  /* - print result */
      
  System.out.println( df.format( d ) );

  /* - print time hour part (in 24-format) */

  Calendar c = df.getCalendar();
  c.setTime( d );

  System.out.println( c.get( Calendar.HOUR_OF_DAY ) );
} 
catch ( ParseException ex ) {}
The output is:
13:52:10
13