In Java, the java.util.Date
class represents a specific moment in time, and the java.util.Calendar
class provides methods for manipulating and formatting dates and times.
Here is an example of how to use the Date
and Calendar
classes to work with dates and times in Java:
import java.util.Calendar; import java.util.Date; import java.util.TimeZone; public class Main { public static void main(String[] args) { // Get the current date and time Date now = new Date(); System.out.println("Current date and time: " + now); // Output: current date and time // Create a Calendar instance Calendar cal = Calendar.getInstance(); // Set the Calendar to the current date and time cal.setTime(now); // Get the year, month, and day from the Calendar int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH); int day = cal.get(Calendar.DAY_OF_MONTH); System.out.println("Year: " + year); // Output: current year System.out.println("Month: " + month); // Output: current month (0-based) System.out.println("Day: " + day); // Output: current day of month // Get the hour, minute, and second from the Calendar int hour = cal.get(Calendar.HOUR_OF_DAY); int minute = cal.get(Calendar.MINUTE); int second = cal.get(Calendar.SECOND); System.out.println("Hour: " + hour); // Output: current hour (24-hour format) System.out.println("Minute: " + minute); // Output: current minute } }Secruo:www.lautturi.com