1

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!

tss
  • 33
  • 1
  • 1
  • 4

3 Answers3

6

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

LocalDateTime now = LocalDateTime.now();
String formatTime = now.getHour() + ":" + now.getMinute();
Scicrazed
  • 542
  • 6
  • 20
  • 3
    This will give you `18:5`, where `18:05` is more standard. Better to use a formatter as in [eric.v’s answer](https://stackoverflow.com/a/49033906/5772882). But using java.time is a good idea. – Ole V.V. Feb 28 '18 at 18:51
3

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")));
eric.v
  • 605
  • 5
  • 9
  • Thanks for you answer! LocalDateTime.parse requires API level 26. I need it to work for 19. Any suggestions? – tss Feb 28 '18 at 16:20
  • @tss java.time, the modern Java date and time API used in this answer, works nicely on Android API level 19. Get ThreeTenABP and add it to your Android project. More details are in [this question: How to use ThreeTenABP in Android Project](https://stackoverflow.com/questions/38922754/how-to-use-threetenabp-in-android-project). – Ole V.V. Feb 28 '18 at 16:40
  • Sorry, I don't really know what is available in Android. It seems that you can access Calendar and some formatter as @assylias just told you – eric.v Feb 28 '18 at 16:41
2

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.

assylias
  • 321,522
  • 82
  • 660
  • 783
  • Thanks for you answer! OffsetDateTime.parse requires API level 26. I need it to work for 19. Any suggestions? – tss Feb 28 '18 at 16:20
  • 1
    You should tag your question with `android` to clarify that you are not using Java SE. You could use a backport such as https://github.com/JakeWharton/ThreeTenABP, or use a SimpleDateFormat and the Calendar class. – assylias Feb 28 '18 at 16:27
  • @tss java.time, the modern Java date and time API used in this answer, works nicely on Android API level 19. As assylias said, get ThreeTenABP and add it to your Android project. More details are in [this question: How to use ThreeTenABP in Android Project](https://stackoverflow.com/questions/38922754/how-to-use-threetenabp-in-android-project). – Ole V.V. Feb 28 '18 at 16:39