Working with Date, Time, and Calendar in Java
Using the Legacy Date Class
The Date object represents a specific instent in time with millisecond precision. Note that many methods in this class are deprecated in favor of Calendar.
getTime(): Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT.getYear(): Returns the year minus 1900. You must add 1900 to get the current year.getMonth(): Returns a value between 0 and 11. You must add 1 to get the standard month number.getDate(): Returns the day of the month (1-31).toLocaleString(): Converts the date to a local timezone representation (deprecated).
// Initialize a new timestamp
java.util.Date now = new java.util.Date();
// Retrieve year (add 1900)
int currentYear = now.getYear() + 1900;
System.out.println("Current Year: " + currentYear);
// Retrieve month (add 1)
int currentMonth = now.getMonth() + 1;
System.out.println("Current Month: " + currentMonth);
// Retrieve day
int dayOfMonth = now.getDate();
System.out.println("Day of Month: " + dayOfMonth);
// Local representation
System.out.println("Local Format: " + now.toLocaleString());
Formattting Dates with SimpleDateFormat
SimpleDateFormat allows for parsing and formatting dates according to a specified pattern.
Common Patterns:
yyyy-MM-dd HH:mm:ss: Standard database format.E: Day in week (e.g., Mon).MMM: Month in year (e.g., Jan).MM: Month in year, zero-padded (e.g., 09).
java.util.Date now = new java.util.Date();
// Standard format
java.text.SimpleDateFormat formatter1 = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(formatter1.format(now));
// Slash separated
java.text.SimpleDateFormat formatter2 = new java.text.SimpleDateFormat("yyyy/MM/dd");
System.out.println(formatter2.format(now));
// Human readable with day name
java.text.SimpleDateFormat formatter3 = new java.text.SimpleDateFormat("yyyy MMM dd E");
System.out.println(formatter3.format(now));
Measuring Time with System.currentTimeMillis()
This method returns the current time in milliseconds since the Unix epoch (1970-01-01 00:00:00 GMT).
long epochMillis = System.currentTimeMillis();
System.out.println("Milliseconds since epoch: " + epochMillis);
// Reconstruct a Date object from the timestamp
java.util.Date reconstructed = new java.util.Date(epochMillis);
System.out.println("Reconstructed Date: " + reconstructed);
The Calendar Class
Calendar is an abstract class that provides methods for converting between an instant in time and a set of calendar fields.
Key Fields:
Calendar.YEAR,Calendar.MONTH(0-indexed),Calendar.DAY_OF_MONTH.Calendar.DAY_OF_WEEK: 1 (Sunday) through 7 (Saturday).Calendar.HOUR_OF_DAY,Calendar.MINUTE,Calendar.SECOND.
java.util.Calendar cal = java.util.Calendar.getInstance();
int y = cal.get(java.util.Calendar.YEAR);
int m = cal.get(java.util.Calendar.MONTH) + 1; // Adjust for 0-index
int d = cal.get(java.util.Calendar.DAY_OF_MONTH);
int weekDay = cal.get(java.util.Calendar.DAY_OF_WEEK) - 1; // Adjust to 0=Sun, 6=Sat
int hour = cal.get(java.util.Calendar.HOUR_OF_DAY);
int minute = cal.get(java.util.Calendar.MINUTE);
int second = cal.get(java.util.Calendar.SECOND);
System.out.printf("%d-%d-%d (Day %d) %02d:%02d:%02d%n", y, m, d, weekDay, hour, minute, second);
Setting Specific Dates
You can clear the current time and set specific fields manually.
java.util.Calendar customCal = java.util.Calendar.getInstance();
customCal.clear();
// Set specific date: September 2, 2025, 21:22:23
customCal.set(java.util.Calendar.YEAR, 2025);
customCal.set(java.util.Calendar.MONTH, 8); // 8 represents September
customCal.set(java.util.Calendar.DATE, 2);
customCal.set(java.util.Calendar.HOUR_OF_DAY, 21);
customCal.set(java.util.Calendar.MINUTE, 22);
customCal.set(java.util.Calendar.SECOND, 23);
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("Custom Date: " + sdf.format(customCal.getTime()));
Type Conversions
Timestamp and Date
// Long to Date
long timestamp = System.currentTimeMillis();
java.util.Date dateFromLong = new java.util.Date(timestamp);
System.out.println(dateFromLong);
// Date to Long
java.util.Date currentDate = new java.util.Date();
long milliseconds = currentDate.getTime();
System.out.println("Timestamp: " + milliseconds);
String and Date
// String to Date
java.text.SimpleDateFormat parser = new java.text.SimpleDateFormat("yyyy年MM月dd日");
try {
java.util.Date parsedDate = parser.parse("2022年02月20日");
System.out.println("Parsed: " + parsedDate);
} catch (java.text.ParseException e) {
e.printStackTrace();
}
// Date to String
java.util.Date now = new java.util.Date();
java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = formatter.format(now);
System.out.println("Formatted String: " + dateString);
Calendar and Date
// Calendar to Date
java.util.Calendar calendarInstance = java.util.Calendar.getInstance();
java.util.Date dateFromCal = calendarInstance.getTime();
// Date to Calendar
java.util.Date inputDate = new java.util.Date();
java.util.Calendar calTarget = java.util.Calendar.getInstance();
calTarget.setTime(inputDate);
Exercise: Printing a Calendar View
The following logic prints a monthly calendar view for a given date, marking the specific day with an asterisk (*).
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;
public class CalendarPrinter {
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter date (yyyy--MM--dd):");
String input = scanner.nextLine();
scanner.close();
DateFormat dateFormat = new SimpleDateFormat("yyyy--MM--dd");
Date d = dateFormat.parse(input);
Calendar cal = Calendar.getInstance();
cal.setTime(d);
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH) + 1;
int targetDay = cal.get(Calendar.DAY_OF_MONTH);
// Reset to first day of month
Date firstDayDate = dateFormat.parse(year + "--" + month + "--1");
cal.setTime(firstDayDate);
int daysInMonth;
if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
daysInMonth = 31;
} else if (month == 4 || month == 6 || month == 9 || month == 11) {
daysInMonth = 30;
} else {
daysInMonth = isLeapYear(year) ? 29 : 28;
}
printMonthView(cal, targetDay, daysInMonth);
}
static boolean isLeapYear(int y) {
return (y % 400 == 0) || (y % 4 == 0 && y % 100 != 0);
}
static void printMonthView(Calendar calendar, int highlightDay, int totalDays) {
System.out.println(" Mon Tue Wed Thu Fri Sat Sun");
int startDay = calendar.get(Calendar.DAY_OF_WEEK);
// Convert Calendar DAY_OF_WEEK to Mon=1 ... Sun=7 logic
int offset = (startDay == 1) ? 6 : startDay - 2;
for (int i = 0; i < offset; i++) {
System.out.print(" ");
}
for (int day = 1; day <= totalDays; day++) {
if ((day + offset) % 7 == 1) {
System.out.println();
}
if (day == highlightDay) {
System.out.print(" * ");
} else {
System.out.printf("%4d ", day);
}
}
System.out.println();
}
}