![]() |
AndroidBerry.com |
Java language has a Built in class called Date which is stored in the java.util.Date package. This class shows the current Time in miliseconds.
If we directly create and display the object of date class, then we will get the output as
import java.util.Date; public class DateEx { public static void main(String[] args) { Date date = new Date(); System.out.println(date); } }
To display only required date or time we have following different methods
Suppose we have two Date objects as
Date date1 = new Date(2018,10,18);
Date date2 = new Date(2020,5,18);
Method | Example | Output |
---|---|---|
boolean after(Date) This method tests if this date is after the specified date. |
date2.after(date1) | true |
boolean before(Date) This method tests if this date is before the specified date. |
date2.before(date1); | false |
boolean compareTo(Date) This method compares two dates. It returns 0 if both are equal. |
date2.compareTo(date1) | false |
long getTime() This method returns the time in miliseconds from January 1,1970, 00:00:00 GMT to current time |
date2.getTime() | 61550562600000 |
String toString() This method converts the Date object into string representation |
date1.toString() | Mon Nov 18 00:00:00 IST 3918 |
Java has DateFormat class to properly display the date and time
import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; public class DateEx { public static void main(String[] args) { DateFormat format = new SimpleDateFormat("dd/MM/yyyy"); Date date1 = new Date(); System.out.println(format.format(date1)); } }