-1

How to get Time without Year,Month,Day from System.currentTimeMillis().

Aju Alex
  • 56
  • 7
  • If you just want the current time without date, just use `LocalTime.now(ZoneId.of("Asia/Kolkata"))` (supply your desired time zone). In any case do consider java.time, see for example the last part of [the answer by Sean Patrick Floyd to the linked original question](https://stackoverflow.com/a/4142428/5772882). – Ole V.V. Aug 05 '19 at 05:02

2 Answers2

3

Better using LocalTime

LocalTime.ofInstant(Instant.ofEpochMilli(System.currentTimeMillis()), ZoneId.systemDefault());
  • You do not get milliseconds if multiplying seconds by 1000. You still get seconds and some zeros. – Christian H. Kuhn Aug 04 '19 at 18:36
  • and, as, I understand, the question is **not** getting milliseconds, but (only) time (second line is superfluous) – user85421 Aug 04 '19 at 18:42
  • The question is about getting time as a `Long`. This is time, as a long. @christian-h-kuhn : Seconds * 1000 are miliseconds, but I agree that its not very useful, as its not accurate. But as the original question was about `getCurrentTimeMillis`, there is maybe a reason for that. – Jordan Lefébure Aug 04 '19 at 18:44
  • question was edited - no `Long`anymore - why delete??? just the second line is wrong – user85421 Aug 04 '19 at 18:46
  • Oh thank you, i did not see, i update the answer then. – Jordan Lefébure Aug 04 '19 at 18:51
  • 1
    just add the `...now()` as additional option (shortcut for above code) – user85421 Aug 04 '19 at 18:52
  • If your Android (min) API level is not yet 26 or higher, you can still use this answer when you add ThreeTenABP to your project. See [this question: How to use ThreeTenABP in Android Project](https://stackoverflow.com/questions/38922754/how-to-use-threetenabp-in-android-project) for a very thorough explanation. – Ole V.V. Aug 05 '19 at 04:55
1

Something like this...

Date date = new Date(System.currentTimeMillis());
DateFormat formatter = new SimpleDateFormat("HH:mm:ss.SSS");
String dateFormatted = formatter.format(date);
Richard Dapice
  • 838
  • 5
  • 10
  • 1
    That's not a `Long`. – CommonsWare Aug 04 '19 at 18:22
  • 1
    He edited that part off... – Richard Dapice Aug 05 '19 at 04:10
  • 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. Today 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`. Yes, you can use it on Android. For older Android see [How to use ThreeTenABP in Android Project](https://stackoverflow.com/questions/38922754/how-to-use-threetenabp-in-android-project). – Ole V.V. Aug 05 '19 at 05:05
  • Maybe the young ones are supporting API 19 and it doesn't support java.time or they don't want another dependency like ThreeTenABP? – Richard Dapice Aug 05 '19 at 15:24