Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting String to Time without Date in Java

Tags:

java

date

How to convert String to Time in java without Date,I need specifically the time alone

String Start_time="04:30";

I used

 DateFormat time=new SimpleDateFormat("hh:mm");
 Time bid_start_time=new Time(time.parse("Start_time").getTime());

I exactly need the value "04:30" in Date format.I don't need the extra Date parameters like DD/MM/YY

like image 385
VijayManohar7 Avatar asked Nov 15 '15 05:11

VijayManohar7


People also ask

How do I get time without date in Java?

To get only time (without date) in the specific format, use the SimpleDateFormat class. That's all about getting time without a date in Java.

How do you convert a string to a time?

Using strptime() , date and time in string format can be converted to datetime type. The first parameter is the string and the second is the date time format specifier. One advantage of converting to date format is one can select the month or date or time individually.


1 Answers

You can't have a Date without the calendar date parts. That's a simple fact of what Date represents:

The class Date represents a specific instant in time, with millisecond precision. ... represent[s] the specified number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT.

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.parse("04:30");

You could prepend the time string with "1970-01-01 ", and then parse e.g. "1970-01-01 04:30", and then just take care to use the time parts of this. I would recommend against that because of the potential not just to use it for only its time parts.

like image 177
Andy Turner Avatar answered Oct 02 '22 13:10

Andy Turner