2

I have some code that creates an ISO8601-formatted timestamp but if the incoming date is in an invalid format, the conversion fails.

I'd like to know if there's a standard way of representing an invalid timestamp in this format?

Wikipedia mentions years prior to 1583 as not being handled under normal operation so my first thought was to simply set the value to something like 0000-01-01T00:00:00Z. If there's a more standard way to indicate an invalid value though, I'd rather use it instead.

Jon Cage
  • 36,366
  • 38
  • 137
  • 215

1 Answers1

1

ISO 8601 does not define a string that represents an invalid timestamp. It only defines what a valid formatted string looks like.

Also, ISO 8601 uses a proleptic Gregorian calendar, which means that all positive years are valid. It allows for negative years (by agreement), but does not define eras such as BC/BCE. In other words, one day before 0001-01-01 would be 0000-12-31 in the proleptic Gregorian calendar. One day before 0000-01-01 would be -0001-12-31 (and year 0 is a leap year).

As far as how you represent "invalid" in your code, that's entirely language and implementation dependent. In many cases, a null would be appropriate. If you are strictly working with strings, then perhaps "" would be better. Hard to say without more context.

Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
  • The data is being exchanged as a JSON string so an empty string sounds like a sensible approach to me. – Jon Cage Nov 27 '17 at 20:26
  • `null` (not as a string) is also valid in JSON. Depending on what it's being deserialized into, it may be more appropriate. For example, as a .Net developer, I might deserialize that field into a `Nullable` (aka. `DateTime?`), in which case the null would automatically come through, but an empty string would be a case I'd have to go out of my way teach the parser how to handle. – Matt Johnson-Pint Nov 27 '17 at 21:16
  • [This answer](https://stackoverflow.com/a/21121267/634824) may also be useful in your decision making. – Matt Johnson-Pint Nov 27 '17 at 21:21
  • That looks great. – Jon Cage Nov 27 '17 at 21:59