Saturday, December 9, 2017

JAVA - How to convert String to time

For conversion use SimpleDateFormat class where you can specify date mask.
import java.text.*;
...
/* - 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 ) {}
Output:
13:52:10
13

No comments:

Post a Comment