Date Class

suggest change

Syntax

Parameters

Parameter | Explanation| —— | —— | No parameter | Creates a new Date object using the allocation time (to the nearest millisecond) | long date | Creates a new Date object with the time set to the number of milliseconds since “the epoch” (January 1, 1970, 00:00:00 GMT) |

Remarks

Representation

Internally, a Java Date object is represented as a long; it is the number of milliseconds since a specific time (referred to as the epoch). The original Java Date class had methods for dealing with time zones, etc., but these were deprecated in favor of the then-new Calendar class.

So if all you want to do in your code is represent a specific time, you can create a Date class and store it, etc. If you want to print out a human-readable version of that date, however, you create a Calendar class and use its formatting to produce hours, minutes, seconds, days, time zones, etc. Keep in mind that a specific millisecond is displayed as different hours in different time zones; normally you want to display one in the “local” time zone, but the formatting methods have to take into account that you may want to display it for some other one.

Also be aware that the clocks used by JVMs do not usually have millisecond accuracy; the clock might only “tick” every 10 milliseconds, and therefore, if timing things, you cannot rely on measuring things accurately at that level.

Import Statement

import java.util.Date;

The Date class may be imported from java.util package.

Caution

Date instances are mutable, so using them can make it difficult to write thread-safe code or can accidentally provide write access to internal state. For example, in the below class, the getDate() method allows the caller to modify the transaction date:

public final class Transaction {
  private final Date date;

  public Date getTransactionDate() {
    return date;
  }
}

The solution is to either return a copy of the date field or use the new APIs in java.time introduced in Java 8.

Most of the constructor methods in the Date class have been deprecated and should not be used. In almost all cases, it is advisable to use Calendar class for date operations.

Java 8

Java 8 introduces new time and date API in the package java.time, including LocalDate and LocalTime. The classes in the java.time package provide an overhauled API that is easier to use. If you are writing to Java 8 it is strongly encouraged that you use this new API. See http://stackoverflow.com/documentation/java/4813/dates-and-time-java-time#t=201611231701424697591 .

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Data Class:
* Date Class

Table Of Contents
8 Arrays
10 Maps
11 Strings
25 JAXB
29 Enums
32 Audio
33 Data Class
41 Scanner
63 Logging
75 Lists
78 Sets
89 JAX-WS
96 XJC
98 Process
106 Modules
114 Applets
122 JNDI
139 JavaBean
141 Literals
144 Packages
150 JMX
153 JShell
159 Sockets
167 Enum Map
175 Hashtable
177 SortedMap