Sebastian Donoso
Sebastian Donoso

Reputation: 61

How do I convert String to Instant concatenating a date string to a time string?

I need to convert this String to a Instant, i do it this way:

String inputStartDate = startDate+" 00:00:00.000";
String inputEndDate = endDate+" 23:59:59.999";

startDate is only the date because i get the String from another call, but i need to keep the hour static, the same way to the endDate.

Then, i convert to Instant like this:

Instant newStarDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse(inputStartDate).toInstant();
Instant newEndDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse(inputEndDate).toInstant();

But when i convert to instant, it's convert wrong. For example:

startDate="2022-02-04"
endDate="2022-02-04"

When i do the concat the string is like this:

inputStartDate: "2022-02-03 00:00:00.000"
inputEndDate: "2022-02-04 23:59:59.999"

And the result when i transform to instant it's like this, i don't know what is wrong.

newStartDate:"2022-02-03T03:00:00Z"
newEndDate:"2022-02-05T02:59:59.999Z"

I need the yyyy-MM-dd HH:mm:ss.SSS to do a mongodb query and it's need to be a Instant.

Upvotes: 1

Views: 3112

Answers (1)

Sebastian Donoso
Sebastian Donoso

Reputation: 61

I got the answer, it was more easier than i think.

Instead of giving it a SimpleDateFormat you have to transform it directly to Instant like this:

Instant finalStartDate = Instant.parse(startDate+"T00:00:00.000Z");
Instant finalEndDate = Instant.parse(endDate+"T23:59:59.999Z");

You have to add the T and the Z.

Upvotes: 2

Related Questions