Is ok to use String data type for timestamp in java?

Viewed 199

I'm having trouble deciding what data type to use to store dates. I think using the Date type will make it easier for the code to be processed by the backend because there are many functions that can be used. But I'm having trouble when it's used for the response API. Each property of data type Date will return a value in the form of a timestamp. Of course this will require effort for the frontend developer to convert it to the actual date.

enter image description here

I've tried several Rest APIs from well-known vendors out there and then I found they use the String data type to process their Rest API requests/responses. Is using the String data type proper to use on date and time?

2 Answers

REST doesn't have a recommended date format, you should select what works best for your end-user and your system.

Generally, people prefer to use ISO 8601 standard for the date-time values in text. The java.time classes use ISO 8601 formats by default when parsing/generating text.

RFC 3339 Date and Time on the Internet is the document to look at that says:

date and time format for use in Internet protocols that is a profile of the ISO 8601 standard for representation of dates and times using the Gregorian calendar.

In your case, you are using epoch for a date which is totally fine and easy to convert to an actual human-readable date using java libraries.

A simple solution would be:

LocalDate ld = Instant.ofEpochMilli(epoch)
            .atZone(ZoneId.systemDefault()).toLocalDate();

It all boils down to arbitrary personal preference. I would personally use string since it is easier to read before sending, in transit, and upon receipt.

Related