Understanding java.util.Date, Calendar, and SimpleDateFormat in Java
This article explains the legacy java.util.Date class, its limited useful constructors and methods, the more flexible java.util.Calendar API, how to format and parse dates with DateFormat and SimpleDateFormat, and best practices for storing timestamps in databases using long values.
java.util.Date object represents an instant precise to milliseconds; however, because Date has existed since JDK 1.0, many of its constructors and methods are deprecated and its use is not recommended due to possible performance or security issues. Below are the few remaining useful constructors and methods that convert between Date and millisecond values:
Constructors Date(): internally calls System.currentTimeMillis() as the date parameter. Date(long date): creates a Date object from the specified long value (milliseconds elapsed since 1970‑01‑01 00:00:00).
Methods boolean after(Date when): tests whether this date is after the specified date. boolean before(Date when): tests whether this date is before the specified date. long getTime(): returns the number of milliseconds between 1970‑01‑01 00:00:00 UTC and this Date. void setTime(long time): sets the time; the meaning of time is the same as in getTime() .
Because Date has shortcomings, the JDK provides java.util.Calendar to handle date and time. Calendar is an abstract class that serves as a template for all calendar types, allowing developers to subclass it for other calendars (e.g., lunar). The default implementation is java.util.GregorianCalendar (the standard Gregorian calendar), and there is also java.util.JapaneseImperialCalendar . Calling Calendar.getInstance() returns a GregorianCalendar instance, internally created via new GregorianCalendar(zone, locale) .
Calendar can freely convert to and from Date. Many Calendar methods require an int field constant such as Calendar.DATE , Calendar.MONTH , Calendar.HOUR , Calendar.DAY_OF_WEEK . Note that Calendar.MONTH is zero‑based (January = 0) and Calendar.DAY_OF_WEEK starts with Sunday = 1.
If a Calendar field is not set, it defaults to the current system time.
add(int field, int amount) can increase (positive amount) or decrease (negative amount) a field; overflow causes carry‑over to larger fields.
roll(int field, int amount) works like add but does not carry over when the field exceeds its range.
set(int field, int value) marks the field as changed but does not recompute the calendar time until the next call to get() , getTime() , getTimeInMillis() , add() or roll() .
Date Formatting
Formatting and parsing between strings and date objects is handled by java.text.DateFormat , an abstract class that provides methods to obtain concrete formatter instances. In practice, developers usually work with its subclass SimpleDateFormat , which is also returned by the various getInstance() methods.
SimpleDateFormat formats Date objects flexibly and parses strings according to a pattern string (not a regular expression). Commonly used methods include format(Date) and parse(String) . The pattern determines the output format, e.g., yyyy-MM-dd HH:mm:ss .
Storing Time in Databases
Because timestamps are affected by time zones, it is recommended to store the number of milliseconds since the epoch (1970‑01‑01 00:00:00 UTC) as a 64‑bit integer (e.g., BIGINT) rather than using database‑specific types like TIMESTAMP or DATETIME. This approach allows the application to format the long value according to the user's time zone when reading it. The drawback is that the raw number is not human‑readable directly in the database.
Conversion from Date to Long is straightforward via date.getTime() .
Conversion from Long to a formatted string uses SimpleDateFormat.format(new Date(longValue)) .
Since a project typically uses a single date‑time format, creating a new formatter each time is unnecessary and can hurt performance. A common practice in Spring applications is to define a singleton Formatter bean and inject it with @Autowired wherever needed.
Original article source: "java一日一条".
Qunar Tech Salon
Qunar Tech Salon is a learning and exchange platform for Qunar engineers and industry peers. We share cutting-edge technology trends and topics, providing a free platform for mid-to-senior technical professionals to exchange and learn.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.