0

I am creating Date object in java.

First way: By using Calender

Date today = Calendar.getInstance().getTime(); 

Second way:

with Date class

Date today1 = new Date();

Which one is most effective way here?

2
  • Calendar is basically doing the same thing, but it's using the settings of the object to generate the result ;) Commented May 28, 2015 at 10:58
  • 1
    Creating an instance of java.util.Date is extremely cheap (just a wrapper around a long-primitive). But using it in formatting (for example in SimpleDateFormat) has some performance impact due to lack of thread-safety, enforced conversion using complex gregorian calendar rules and/or use of synchronization overhead. Commented May 28, 2015 at 11:00

3 Answers 3

3

Since Java 8 you should go for LocalDateTime or LocalDate:

LocalDateTime timePoint = LocalDateTime.now(
    );     // The current date and time
LocalDate.of(2012, Month.DECEMBER, 12); // from values

LocalDate theDate = timePoint.toLocalDate(); // or
theDate = LocalDate.now(); // 

Fromt the documentation:

[For example, the existing classes (such as java.util.Date and SimpleDateFormatter) aren’t thread-safe, leading to potential concurrency issues for users—not something the average developer would expect to deal with when writing date-handling code.

Some of the date and time classes also exhibit quite poor API design. For example, years in java.util.Date start at 1900, months start at 1, and days start at 0—not very intuitive.]1

Sign up to request clarification or add additional context in comments.

Comments

2

If you have to decide between the two. Take the new Date(). As the Calendar.getInstance().getTime() would create a Calendar instance which you could not use afterwards.

Comments

0

You can use this too! Date newDate = new GregorianCalendar(year, month, day).getTime();

Within your options, I will prefer the first alternative.

3 Comments

Why are you prefer this?. Is there any thing specific to use this?
but how do you figure out what the year, month, day is?
I want to create today's date.. how can i use your code?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.