-1

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 ?
Andre Proenza
  • 149
  • 1
  • 10
  • Hi @AndreProenza - have a look at this answer to a previous question https://stackoverflow.com/a/4216767/15310387. If you still have issues, then please update the question with what you've tried that isn't working ... ALSO have a think about the hour case - is that TODAY 23:59 or some other date ...?? – Mr R Apr 09 '21 at 01:05
  • 1
    How can a date have zero for either month or day-of-month? – Basil Bourque Apr 09 '21 at 01:30
  • 3
    Does this answer your question? [Java string to date conversion](https://stackoverflow.com/questions/4216745/java-string-to-date-conversion) – VWeber Apr 09 '21 at 10:57
  • What did your search bring up? How did it fall short? – Ole V.V. Apr 09 '21 at 14:11

2 Answers2

2

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.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
0

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();
    }
Ksh
  • 36
  • 2
  • 1
    Please don’t teach the young ones to use the long outdated and notoriously troublesome `SimpleDateFormat` class. At least not as the first option. And not without any reservation. We have so much better in [`java.time`, the modern Java date and time API,](https://docs.oracle.com/javase/tutorial/datetime/) and its `DateTimeFormatter`. – Ole V.V. Apr 09 '21 at 11:41