Reputation: 445
I have a String object which stores the current system time in HH:mm format. I have to convert this to a DATE object and maintain the same HH:mm format. How can this be done.
I tried using Date parse options but everytime I get the response in complete dd-MM-yyyy HH:mm:ss format and not in the required HH:mm format needed.
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
String getCurrentTime = sdf.format(Calendar.getInstance().getTime());
Date date = sdf1.parse(getCurrentTime);
Expected output should be a Date result in HH:mm format.
Upvotes: 3
Views: 2625
Reputation: 31
Like mentioned in the comments, Date is an object. Other way around with Date/Time API:
LocalTime time = LocalTime.now(); //current time
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss"); //set format
System.out.println(time.format(formatter));
Upvotes: 3
Reputation: 13855
Here is the simple example to solve this using java8 Date and Time API:
DateTimeFormatter parser1 = DateTimeFormatter.ofPattern("HH:mm:ss");
LocalDateTime ldd1 = LocalDateTime.now();
System.out.println("DateTimeFormatter ldd1 = " + parser1.format(ldd1));
Upvotes: 1
Reputation: 3059
Instead of using Date
use java.time.LocalTime
. Example:
LocalTime localTime = LocalTime.now();
This class does not store and represent a date or time-zone. You can use the LocalTime.now()
and LocalTime.of()
methods to create the current time and specific time object respectively.
You can use the getHour()
, getMinute()
and getSecond()
methods of the LocalTime
class to get hour, minute and second respectively.
You can use the plus
and minus
methods of the LocalTime
class to add or subtract hours, minutes etc.
You can use the compareTo()
, isAfter()
and isBefore()
methods of the LocalTime
class to compare the LocalTime
objects.
Upvotes: 1
Reputation: 3600
You are expecting the output of parse
to be a Date
object in format HH:mm
but this will never be the case because it is eventually a Date
object. It will have information of date,month,year, time etc i.e. it is made to store both date and time information.
You get the information HH:mm
using the format
method which you did and it does give you that information
If you want only information of Hour and minutes, I suggest you to create a new class and populate it's value based on output of format
method
Upvotes: 1