2

I cannot figure out how to tell if a Calendar object was created with no milliseconds versus a Calendar object that was created with milliseconds that happens to have a value 0.

I need to distinguish between the time stamps

2018 04 30 13:44:55 -0500
and
2018 04 30 13:44:55.000 -0500

The latter shows that the time clock is reporting time with a resolution to milliseconds while the former is only reporting time with a resolution to seconds. So in the latter case I want to display the '000' but in the former I do not.

Calendar.get(Calendar.MILLISECONDS) = 0 clearly does not solve this problem. Any ideas on how to do this?

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Brian Reinhold
  • 2,313
  • 3
  • 27
  • 46
  • What is the context? Can `Calendar` be avoided, and use a `LocalDateTime`? – Andrew S May 07 '18 at 12:55
  • For new time classes: `LocalDateTime.isSupported(ChronoField.MILLI_OF_SECOND)` – Joop Eggen May 07 '18 at 13:07
  • 1
    @JoopEggen That will always return true. `LocalDateTime` has precision of nanoseoncds. Always. – Ole V.V. May 07 '18 at 23:28
  • Brian, what is the scenario in which you need this? I was thinking, if you are parsing a date-time string that either has milliseconds in it or not, and you need to give the same string back, you might just keep the string around in addition to your (as I recommend) `OffsetDateTime` object. It’s redundant, but might solve your problem? (The `Calendar` class is long outmoded and poorly designed, so I would avoid that.) – Ole V.V. May 10 '18 at 02:29
  • At the moment I am kind of stuck with Calendar since libraries I need use it. – Brian Reinhold May 28 '18 at 09:16
  • @AndrewS `LocalDateTime` is the wrong class to use, as it does *not* represent a moment. `ZonedDateTime` is the replacement for `Calendar`. And `Instant` replaces `java.util.Date` for a moment in UTC. – Basil Bourque Aug 05 '18 at 19:54

1 Answers1

2

The Calendar::isSet(int) method will test if a specific field has been set.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • Indeed, `new GregorianCalendar(2018, Calendar.JANUARY, 22, 23, 59, 48).isSet(Calendar.MILLISECOND)` yields `false`. – Ole V.V. May 07 '18 at 14:52
  • Yes, I discovered that and gave it a try and it did indeed solve my problem. I must also being doing something wrong on stack overflow; I never get notifications in my email of any responses to my questions or comments ... though I believe I have correctly signed up for them ... – Brian Reinhold May 19 '18 at 12:45