0

Most of the methods e.g. getYear() getMonth() are depricated and mentions to use Calendar.get(Calendar.MONTH) instead.

However, as mentioned here, in order to do that, we would need to write:

Calendar cal = Calendar.getInstance();
cal.setTime(date);

Also, Calendar.getInstance() does not return same instance of Calendar, but returns a new instance always.

Is there a faster way to get Year, Month, Day, etc from Date, instead of creating Calendar instance and setting date and then getting the required information?

In other words, is there any more performant way to achieve so?

Community
  • 1
  • 1
Sandeep Jindal
  • 14,510
  • 18
  • 83
  • 121
  • 4
    You're worrying too much for new instance creation. With current JVM, the cost of creating an object like `Calendar` is negiglible. – morgano May 18 '15 at 00:10
  • 3
    Use the Java 8 Time API or JodaTime... – MadProgrammer May 18 '15 at 00:13
  • FYI, in high volume on an Intel MacBook, (a) `Instant.now()` (replaces `java.util.Date`) takes ≈ 65 nanoseconds, (b) `ZonedDateTime.now( ZoneId )` (replaces `Calendar`) takes ≈ 255 nanoseconds, and (c) `LocalDate` (replaces `java.sql.Date`) takes ≈ 210 nanos. Not likely a bottleneck in your app. – Basil Bourque Oct 20 '18 at 00:31

1 Answers1

0

GregorianCalendar or SimpleDateFormat, but I guess if you want more uses and want to be more specific you can use http://www.joda.org/joda-time/

source: Get Today's date in Java at midnight time

Community
  • 1
  • 1
0x2B
  • 91
  • 9