Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert String in time to Time object without Date

Tags:

java

date

time

i got problem to convert String time to Time object because it print together 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 will be better if you could give an example.

thank you.

like image 224
syafikah Avatar asked Mar 27 '11 17:03

syafikah


People also ask

How do you convert a string to a time?

We can convert a string to datetime using strptime() function. This function is available in datetime and time modules to parse a string to datetime and time objects respectively.

How do I get a time without date in Java?

You can use LocalTime in java. time built into Java 8 and later (Tutorial), or LocalTime from Joda-Time otherwise. These classes represent a time-of-day without a date nor a time zone. LocalTime localTime = LocalTime.

How do you convert a date without time in Python?

date. isoformat() Return a string representing the date in ISO 8601 format, 'YYYY-MM-DD'. For example, date(2002, 12, 4). isoformat() == '2002-12-04'.


1 Answers

Use the same SimpleDateFormat that you used to parse 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, the Date object always represents a combined date/time value. It can't properly represent a date-only or time-only value, so you have to use the correct DateFormat to ensure you only "see" the parts that you want.

like image 193
skaffman Avatar answered Oct 05 '22 20:10

skaffman