Java 8 Update
Java 8 introduces the following packages for time and date manipulation.
java.time.*;
java.time.format.*;
java.time.chono.*;
java.time.temporal.*;
java.time.zone.*;
These are more organized and intuitive.
We need only top two packages for the discussion.
There are 3 top level classes - LocalDate
, LocalTime
, LocalDateTime
for describing Date, Time and DateTime respectively. Although, they are formatted properly in toString()
, each class has format method which accepts DateTimeFormatter
to format in customized way.
DateTimeFormatter
can also be used show the date given a day. It has few
import java.time.*;
import java.time.format.*;
class DateTimeDemo{
public static void main(String...args){
LocalDateTime x = LocalDateTime.now();
System.out.println(x.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL)));//Shows Day and Date.
System.out.println(x.format(DateTimeFormatter.ofPattern("EE")));//Short Form
System.out.println(x.format(DateTimeFormatter.ofPattern("EEEE")));//Long Form
}
}
ofLocalizedTime
accepts FormatStyle
which is an enumeration in java.time.format
ofPattern
accepts String
with restricted pattern characters of restricted length. Here are the characters which can be passed into the toPattern
method.
You can try different number of patterns to see how the output will be.
Check out more about Java 8 DateTime API here