Table of Contents
✅ Use java.time instead of Old Date/Calendar Classes
? 1. Get Current Date and Time
?️ 2. Create Specific Dates
➕ 3. Add or Subtract Time (Immutably)
? 4. Work With Time Zones (ZonedDateTime)
? 5. Format and Parse Dates
? 6. Legacy Compatibility (if needed)
? Pro Tips
Home Java javaTutorial How to work with Calendar in Java?

How to work with Calendar in Java?

Aug 02, 2025 am 02:38 AM
java calendar

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime, and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to the use of the java.time API, which provides a clear, immutable and thread-safe interface, suitable for most practical scenarios, and can effectively avoid the defects of traditional date classes.

How to work with Calendar in Java?

Working with calendars in Java can be confusing if you're using outdated methods, but modern Java (especially from Java 8 onward) provides a much cleaner and independent way to handle dates and times via the java.time package. Here's a practical guide on how to work with calendars effectively.

How to work with Calendar in Java?

✅ Use java.time instead of Old Date/Calendar Classes

Avoid the old java.util.Date and java.util.Calendar classes — they're mutable, not thread-safe, and hard to work with. Instead, use the java.time API introduced in Java 8 .

Key classes:

How to work with Calendar in Java?
  • LocalDateTime – Date and time without timezone
  • ZonedDateTime – Date and time with timezone
  • LocalDate – Just a date (eg, 2025-04-05)
  • LocalTime – Just a time (eg, 14:30)
  • YearMonth , MonthDay , etc. – Specialized date types

? 1. Get Current Date and Time

 import java.time.LocalDateTime;
import java.time.LocalDate;
import java.time.LocalTime;

LocalDateTime now = LocalDateTime.now();
System.out.println("Now: " now);

LocalDate today = LocalDate.now();
System.out.println("Today: " today);

LocalTime time = LocalTime.now();
System.out.println("Current time: " time);

This gives you clean, immutable objects representing the current moment.


?️ 2. Create Specific Dates

You can create fixed dates easily:

How to work with Calendar in Java?
 LocalDate birthday = LocalDate.of(1990, 5, 15); // Year, Month, Day
// Or use Month enum
LocalDate xmas = LocalDate.of(2025, java.time.Month.DECEMBER, 25);

Similarly for time:

 LocalTime meetingTime = LocalTime.of(14, 30); // 2:30 PM

Combine date and time:

 LocalDateTime event = LocalDateTime.of(2025, 3, 20, 9, 0); // Mar 20, 9:00 AM

➕ 3. Add or Subtract Time (Immutably)

All java.time objects are immutable , so you get a new instance when modifying.

 LocalDate today = LocalDate.now();
LocalDate nextWeek = today.plusWeeks(1);
LocalDate nextMonth = today.plusMonths(1);
LocalDate tenDaysAgo = today.minusDays(10);

System.out.println("Next week: " nextWeek);

Works similarly for LocalDateTime , LocalTime , etc.


? 4. Work With Time Zones (ZonedDateTime)

If you need time zones (eg, scheduled across regions):

 import java.time.ZoneId;
import java.time.ZonedDateTime;

ZoneId nyZone = ZoneId.of("America/New_York");
ZonedDateTime nyTime = ZonedDateTime.now(nyZone);

ZoneId londonZone = ZoneId.of("Europe/London");
ZonedDateTime londonTime = ZonedDateTime.now(londonZone);

System.out.println("NY: " nyTime);
System.out.println("London: " londonTime);

You can also convert between zones:

 ZonedDateTime nyInLondonTime = nyTime.withZoneSameInstant(londonZone);

? 5. Format and Parse Dates

Convert to/from strings using DateTimeFormatter .

 import java.time.format.DateTimeFormatter;

LocalDate date = LocalDate.of(2025, 4, 5);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
String formatted = date.format(formatter); // "05-04-2025"
System.out.println(formatted);

// Parse string back to date
String input = "15-08-2023";
LocalDate parsed = LocalDate.parse(input, formatter);

Common patterns:

  • "yyyy-MM-dd" → 2025-04-05
  • "dd/MM/yyyy HH:mm" → 05/04/2025 14:30
  • "MMM dd, yyyy" → Apr 05, 2025

? 6. Legacy Compatibility (if needed)

If you must interact with old APIs that use java.util.Date :

 import java.util.Date;
import java.time.Instant;

// Convert LocalDateTime to Date
LocalDateTime ldt = LocalDateTime.now();
Date oldDate = Date.from(ldt.atZone(ZoneId.systemDefault()).toInstant());

// Convert Date to LocalDateTime
Date legacyDate = new Date();
LocalDateTime ldt2 = legacyDate.toInstant()
                               .atZone(ZoneId.systemDefault())
                               .toLocalDateTime();

But try to stick with java.time throughout your app.


? Pro Tips

  • Always specify time zones explicitly when dealing with real-world events.
  • Use Instant for timestamps (eg, logging, database storage).
  • For recurring events or calendar logic (eg, "first Monday of the month"), consider libraries like ThreeTen-Extra or Joda-Time (though Joda is now in maintenance mode).

Basically, working with calendars in Java is clean and safe if you use java.time . Avoid the old Calendar class unless you're maintaining legacy code. Focus on LocalDate , LocalDateTime , ZonedDateTime , and formatting tools — they cover most real-world use cases.

The above is the detailed content of How to work with Calendar in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Solving Common Java NullPointerException Issues with Optional Solving Common Java NullPointerException Issues with Optional Aug 31, 2025 am 07:11 AM

Optional is a container class introduced by Java 8. It is used to clearly indicate that a value may be empty, thereby avoiding NullPointerException; 2. It simplifies nested null checking by providing map, orElse and other methods, preventing methods from returning null and standardizing collection return values; 3. Best practices include only returning values, avoiding the use of fields or parameters, distinguishing orElse from orElseGet, and not calling get() directly; 4. Optional should not be abused. If non-empty methods do not need to be wrapped, unnecessary Optional operations should be avoided in the stream; correct use of Optional can significantly improve code security and readability, but it requires good programming habits.

Edit bookmarks in chrome Edit bookmarks in chrome Aug 27, 2025 am 12:03 AM

Chrome bookmark editing is simple and practical. Users can enter the bookmark manager through the shortcut keys Ctrl Shift O (Windows) or Cmd Shift O (Mac), or enter through the browser menu; 1. When editing a single bookmark, right-click to select "Edit", modify the title or URL and click "Finish" to save; 2. When organizing bookmarks in batches, you can hold Ctrl (or Cmd) to multiple-choice bookmarks in the bookmark manager, right-click to select "Move to" or "Copy to" the target folder; 3. When exporting and importing bookmarks, click the "Solve" button to select "Export Bookmark" to save as HTML file, and then restore it through the "Import Bookmark" function if necessary.

LOL Game Settings Not Saving After Closing [FIXED] LOL Game Settings Not Saving After Closing [FIXED] Aug 24, 2025 am 03:17 AM

IfLeagueofLegendssettingsaren’tsaving,trythesesteps:1.Runthegameasadministrator.2.GrantfullfolderpermissionstotheLeagueofLegendsdirectory.3.Editandensuregame.cfgisn’tread-only.4.Disablecloudsyncforthegamefolder.5.RepairthegameviatheRiotClient.

Enter key not working on my keyboard Enter key not working on my keyboard Aug 30, 2025 am 08:36 AM

First,checkforphysicalissueslikedebrisordamageandcleanthekeyboardortestwithanexternalone;2.TesttheEnterkeyindifferentappstodetermineiftheissueissoftware-specific;3.Restartyourcomputertoresolvetemporaryglitches;4.DisableStickyKeys,FilterKeys,orToggleK

What is a memory leak in Java? What is a memory leak in Java? Aug 28, 2025 am 05:37 AM

AmemoryleakinJavaoccurswhenunreachableobjectsarenotgarbagecollectedduetolingeringreferences,leadingtoexcessivememoryusageandpotentialOutOfMemoryError.Commoncausesincludestaticcollectionsretainingobjectsindefinitely,unclosedresourceslikestreamsorconne

What are wrapper classes and why are they used in Java? What are wrapper classes and why are they used in Java? Sep 01, 2025 am 05:58 AM

Wrapperclassesareusedtoconvertprimitivedatatypesintoobjects,enablingtheiruseincollections,allowingnullvalues,providingutilitymethods,andsupportingautoboxing/unboxing.1.TheyallowprimitivestobeusedincollectionslikeArrayList,whichonlyacceptobjects.2.The

How to find the max or min value in a Stream in Java How to find the max or min value in a Stream in Java Aug 27, 2025 am 04:14 AM

Use the max() and min() methods to combine Comparator to find the maximum and minimum values ​​in the stream, such as Comparator.naturalOrder() or Integer::compareTo compare basic types; 2. For custom objects, use Comparator.comparing() to compare based on specific fields, such as Person::getAge; 3. Since the result is Optional, the empty stream situation must be handled. You can use isPresent() to check or orElse() to provide default values. It is recommended to use IntStream for basic types to avoid boxing overhead and improve performance. In the end, you should always be properly done.

CVE-2024-20674|Windows Kerberos security function bypasses vulnerability CVE-2024-20674|Windows Kerberos security function bypasses vulnerability Sep 02, 2025 pm 05:18 PM

0x00 Foreword Kerberos was created by MIT as a solution to these cybersecurity issues. Is a client/server architecture that provides security verification processing over the network. Through verification, the identity of the sender and receiver of network transactions can be ensured to be true. The service can also verify the validity (integrity) of data passed back and forth and encrypt the data during transmission (confidentiality). 0x01 Vulnerability Description An attacker with access to a victim network can exploit this vulnerability by establishing an intermediate (MITM) attack or other local network spoofing techniques, and then sending a malicious Kerberos message to the client victim's computer and pretending to be a Kerberos authentication server. 0x02CVE

See all articles