How can i convert these two strings each one to a respective Date in java?
String day = "2021-05-9" -> Date ?
String hour = "23:59:00" -> Date ?
How can i convert these two strings each one to a respective Date in java?
String day = "2021-05-9" -> Date ?
String hour = "23:59:00" -> Date ?
Parse as the appropriate java.time type.
LocalDate ld = LocalDate.parse( "2021-05-23" ) ;
LocalTime lt = LocalTime.parse( "23:00:00" ) ;
If by Date
you meant java.util.Date
, that terrible class was supplanted years ago by the modern java.time classes defined in JSR 310. Never use Date
.
Also, the java.util.Date
class represents a moment as seen in UTC. If combining your date and time, we would still be lacking the context of an offset-from-UTC or time zone.
If you want to combine your date and time, use LocalDateTime
class.
LocalDateTime ldt = LocalDateTime.of( ld , lt ) ;
But be aware that this class cannot represent a moment, is not a point on the timeline, as it does not have an offset or time zone.
You can try this.
try {
String day = "2021-05-09";
String hour = "23:59:00";
Date dt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(day + " " + hour);
System.out.println(dt);
}catch (ParseException e) {
e.printStackTrace();
}