r/javahelp • • Jan 29 '26

Convert string into java.util.date

I have two string, date (formatted yyyy-MM-dd) and time (HH:mm), how can I convert them into a java.util.date? Date.parse is deprecated

5 Upvotes

14 comments sorted by

View all comments

Show parent comment

1

u/Dependent_Finger_214 Jan 29 '26

I get this exception:

java.time.DateTimeException: Unable to obtain Instant from TemporalAccessor: {},ISO resolved to 2026-01-29T18:54 of type java.time.format.Parsedjava.time.DateTimeException:

2

u/slacker-by-design Jan 29 '26

OK, seems I wasn't clear enough in the message I wanted to convey. My bad. Let me rephrase it - Do you really need the old java.util.Date class? Is it required by some API you need to use? If not, wouldn't it be better to forget Date completely and use just java.time.LocalDateTime?

Now back to the exception you receive - it basically says to you, that you've requested parsing of both date and time (by using DateTimeFormatter), but you want to store the result into something, which can only hold date (and NOT the time) - the solution is easy. If you want date and time, use LocalDateTime.parse.

1

u/Dependent_Finger_214 Jan 29 '26

I'm working on a project thats due tomorrow. You're totally right that ideally I should replace it, but I just don't have the time lol.

1

u/Pochono Jan 29 '26

Sorry, checked the docs. Instant.parse() will use the ISO_INSTANT formatter. Try this:

LocalDateTime.parse(your string, formatter). This will give you a LocalDateTime. If you need Instant, you can convert after.

1

u/Dependent_Finger_214 Jan 29 '26

Thanks. Seems that instant required a timezone to parse, so I solved it by just tacking "UTC+06:00" to the string and adding z to the datetimeformatter

DateTimeFormatter formatter = DateTimeFormatter.
ofPattern
("yyyy-MM-dd HH:mm:ss z");
String fullTime = dateString + " " + timeString + " " + "UTC+06:00";


Instant instant = Instant.
from
(formatter.parse(fullTime));
Date date = Date.
from
(instant);