tss
tss

Reputation: 33

Get time of day from local datetime string

I have a string that looks like this:

String localTimeString = "2018-03-01T17:20:00.000+01:00";

What's the right approach to get only the time of day in this string, in format "HH:mm"?

(Min sdk is set to 19)

All help appreciated!

Upvotes: 1

Views: 15017

Answers (3)

Scicrazed
Scicrazed

Reputation: 602

You can just grab the hours and minutes from the LocalDateTime and concatenate them.

LocalDateTime now = LocalDateTime.now();
String formatTime = now.getHour() + ":" + now.getMinute();

Upvotes: 6

eric.v
eric.v

Reputation: 615

Parse your string to a LocalDateTime

String localTimeString = "2018-03-01T17:20:00.000+01:00";
LocalDateTime ldt = LocalDateTime.parse(localTimeString, DateTimeFormatter.ISO_DATE_TIME);

And then format it to output hours and minutes

System.out.println(ldt.format(DateTimeFormatter.ofPattern("HH:mm")));

Upvotes: 4

assylias
assylias

Reputation: 328649

Your string is in a standard ISO format, so you can parse it easily with:

OffsetDateTime.parse(localTimeString)

Now you just want the time component, and you need a string representation:

String time = OffsetDateTime.parse(localTimeString).toLocalTime().toString();

which outputs "17:20". Note that this works because there are no seconds in the original string, otherwise they would also appear in the output.

Upvotes: 3

Related Questions