C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
DateFormat: This class provides the parse method. With parse, we can convert a String into its Date representation.
Date: This represents a point in time. The DateFormat parse method returns a Date instance.
Calendar: With Calendar we access values from the Date. We can set a Calendar and get values, like hours, from it.
Java program that uses Calendar
import java.text.DateFormat;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
public class Program {
public static void main(String[] args) throws ParseException {
// Get DateFormat and parse a String into a Date.
DateFormat format = DateFormat.getInstance();
Date date = format.parse("05/14/14 1:06 PM");
// Set date in a Calendar.
Calendar cal = Calendar.getInstance();
cal.setTime(date);
// Get hours from the Calendar.
int hours = cal.get(Calendar.HOUR_OF_DAY);
if (hours == 13) {
System.out.println(true);
}
}
}
Output
true
CompareTo: This returns negative one, 0 or one. The int indicates the relative order of the two Calendars.
Java program that uses after, before, compareTo
import java.util.Calendar;
public class Program {
public static void main(String[] args) {
// Set date to 5/13.
Calendar cal = Calendar.getInstance();
cal.set(2014, 5, 13);
// Set date to 5/14.
Calendar cal2 = Calendar.getInstance();
cal2.set(2014, 5, 14);
// See if first date is after, before second date.
boolean isAfter = cal.after(cal2);
boolean isBefore = cal.before(cal2);
System.out.println(isAfter);
System.out.println(isBefore);
// Compare first to second date.
int compare = cal.compareTo(cal2);
System.out.println(compare);
}
}
Output
false
true
-1