How to Hardcode Date in Java with Examples


If you want to hardcode the value for a date in Java then you can make use of the java.time.LocalDate (Java 8 and above) or java.util.Date (pre-Java 8)

Let's take a look at some examples.


Example 1: Using Java 8 or above java.time.LocalDate

LocalDate date = LocalDate.of(2023, 12, 25);

Example 2: Using Java 8 or above Instant

Instant instant = Instant.parse("2023-12-25T00:00:00.00Z");

Example 3: Using Java 6 or above Calendar

Calendar calendar = Calendar.getInstance();
calendar.set(2023, 11, 25);

Example 4: Using Java 7 or before SimpleDateFormat

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = dateFormat.parse("2023-12-25");

Example 5: Using Java 7 or before java.util.Date

Date date = new Date(123, 11, 25);

You will need to add @SuppressWarnings("deprecation") as deprecated - should be avoided!

Preferred way!

hardcode date in Java example

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap