Convert string in time to a time object without date

I am having a problem converting a String time to Time object because it prints with Date. this is my code.

String time = "15:30:18"; DateFormat sdf = new SimpleDateFormat("hh:mm:ss"); Date date = sdf.parse(time); System.out.println("Time: " + date); 

how to convert and print Time only without date in java. it would be better if you could give an example.

thanks.

+8
source share
3 answers

Use the same SimpleDateFormat that you used to analyze it:

 String time = "15:30:18"; DateFormat sdf = new SimpleDateFormat("hh:mm:ss"); Date date = sdf.parse(time); System.out.println("Time: " + sdf.format(date)); 

Remember that a Date object always represents a combined date / time value. It cannot correctly represent a value only for a date or time, so you should use the correct DateFormat to make sure that you only see the parts that you want.

+24
source

It also works

 String t = "00:00:00" Time.valueOf(t); 
+8
source

Joda-Time | java.time

If you need a time value with no date and no time zone, you should use either the Joda-Time library or the new java.time package in Java 8 (inspired by Joda-Time).

Both of these structures offer the LocalTime class.

In Joda-Time 2.4 ...

 LocalTime localTime = new LocalTime( "15:30:18" ); 

In java.time ...

 LocalTime localTime = LocalTime.parse( "15:30:18" ); 
+4
source

All Articles