Strict JSON time parsing with custom UnmarshalJSON

12188
0

Time parsing bugs are common in APIs: clients send different formats, empty strings, or timezone-less values. I like making time parsing explicit by wrapping time.Time and implementing UnmarshalJSON. The wrapper accepts RFC3339, treats null as “unset,” and rejects anything else. That gives you clear 400 errors instead of weird “zero time” values drifting into the database. I also implement MarshalJSON so the server emits a consistent format, which makes caching and client parsing easier. The key is to keep semantics tight: if a field is optional, make it a pointer or allow null; if it’s required, validate it. This pattern prevents subtle bugs in scheduling and billing systems where a single timezone mistake can cause real customer impact.