Top 25 Java Date, Time, and Calendar Interview Questions Answers

The Date and Time API is a very important one for day to day Java development work but many interviewers don't ask enough questions on this topic. Most of the questions are based on either Java Collection framework like  HashMap, ConcurrentHashMap, or ArrayList or on multi-threading concepts like volatile, synchronized, and atomic variables. This is not good and I think many interviewers have realized that a good understanding of date and time API is also important for a good Java developer. That's the main reason for an increasing number of date, time, and calendar-based Java interview questions in recent times, particularly in the last couple of years.

Since Java development job market is very good at this moment and there are a lot of jobs open, particularly in investment banking domain in the Asia Pacific, its probably the best time to change your job, especially if you are stuck with no learning, no salary increment and not a significant bonus or incentives in last a couple of years.

Apart from stability, growth is very important because if you don't move forward you will be stuck and eventually move backward, hence changing job is as important as sticking to a job which is working for you.

Btw, if you are new to Java and don't know much about Date and Time classes then I suggest you to first go through a comprehensive course like The Complete Java Masterclass on Udemy. It's also recently updated to cover the latest Java version and not very expensive. You can get it in just $10 in several Udemy flash sales which happens all around the year.

Top 10 Date, Time and Calendar Interview Questions and Answers

I have been sharing interview questions on various Java topics from last a couple of years like multithreading, collections, design patterns, coding problems, etc, but one topic which I haven't touched yet was date and time and that's why I thought to share some of the interesting Date and time-based questions from recent Java interviews. In this article, you will find those.

1. Does SimpleDateFormat be safe to use in the multithreaded program? (answer)

No, unfortunately, DateFormat and all its implementations including SimpleDateFormat is not thread-safe, hence, should not be used in the multi-threaded program until external thread-safety measures are applied e.g. confining SimpleDateFormat object into a ThreadLocal variable. I

f you don't do that, you will get an incorrect result while parsing or formatting dates in Java. Though, for all practical date-time purposes, I highly recommend the joda-time library.

25 Java Date, Time, and Calendar Interview Questions Answers

2. How do you format a date in Java? like in the ddMMyyyy format? (answer)

You can either use the SimpleDateFormat class or joda-time library to format the date in Java. DateFormat class allows you to format date on many popular formats. Please see the answer for code samples to format the Date into different formats like dd-MM-yyyy or ddMMyyyy.

3. Can you tell some differences between old and new Date Time API of Java 8?

Even though new Date and Time API are a completely new API, you can deduce the following difference between them:
1) In old API, Date was mutable but in Java 8 all date and time classes like LocalDate, LocalTime or LocalDateTime are Immutable.
2) In old API, SimpleDateFormat was not thread-safe, but in Java 8 Formatter are thread-safe.
3) In old Date and Calendar API, Year starts with 1900, Months starts with 0, which is corrected in Java 8, here numbers make more sense.
4) Old Date and Calendar API has just one class Date to represent date and time, but Java 8 has separated classes for Date and Time e.g. LocalDate and LocalTime

4. Which date the following Date instance represent?

Date aDate = new Date(2015, 12, 25, 20, 40);

This is a really tricky question for any casual Java developers who have not written date and time-based code for himself because this will not represent the Christmas day or 25th December 2015. This code has got two bugs, first, the year starts from 1900 to, to represent 2015, you need to pass 115 i.e. 2015-1900.

The second issue with this code is that the month is not correct. The month starts from 0, so December would 11 not 12, interesting right? That's why you should new Date and Time API from Java 8, which solves all these issues. Again, you can check The Complete Java Masterclass to learn more about new Date and Time API.

Top 10 Java Date, Time and Calendar Interview Questions Answers

5. How do you copy a Date in Java? (answer)

It's a simple question to answer. The Date class implements the clone() method, so just call date.clone() to create a copy of the Date object in Java.

6. What is the relationship between java.sql.Date and java.util.Date? (answer)

This is one of the very interesting questions as not many developers know this fine but obvious detail. The java.sql.Date extends java.util.Date and suppress all time-related methods to act as just a date class. This is in direct violation of the Liskov substitution principle.

7. Can you format Calendar in Java? (answer)

No, Calendar cannot be formatted in Java. You can only format dates.

8. How do you convert a Calendar to Date and vice-versa? (answer)

Well, you can use the Calendar.setTime() and Calendar.getTime() method to convert the Calendar to Date and vice-versa.

9. What is the equivalent of Date class in Java 8? (answer)

The Instance class is the equivalent to java.util.Date in Java 8 because it also represents a millisecond value or an instance in the timescale. Java 8 has also added conversion method e.g. toInstant() and fromDate() to convert instance to java.util.Date and vice-versa. See Java SE 8 for Really Impatient By Cay S. Horstmann for more details.

Top 10 Java Date, Time and Calendar Interview Questions Answers

10. How do you convert a millisecond to Date in Java? (answer)

One of the simplest questions to answer, you can call the getTime() method which returns the millisecond from the Epoch.

12. How do you get a month and year from a Date object in Java? (answer)

You can convert a Date to Calendar and then use its get() method with various fields to get the month, year, day of the week and other date particulars e.g.

int day = calendar.get(Calendar.DATE); // returns the day
int month = calendar.get(Calendar.MONTH) + 1; // month starts from 0
int year = calendar.get(Calendar.YEAR) + 1900; // year starts from 1900

13. How do you convert XMLGregorianCalendar to Date in Java? (answer)

I have discussed this problem before, please check the link for the detailed answer.

14. How do you get the current time in GMT in Java? (answer)

The Java date is independent of time and display time in a current time zone only if you print them. So, in order to convert the current time in GMT, you need to use Calendar with a time zone as shown in the given answer.

15. Is Date class be Immutable in Java? (answer)

No, the Date is not immutable. You can change it's internal to represent a different date. This is the reason that when you have a member represent Date, you must be careful not to leak its reference outside using getDate() method, because then the client can modify the state of the Immutable object, instead a copy should be returned to the client as suggested in Effective Java book by none other than Joshua Bloch, author of several key classes of JDK API.

Java Date, Time and Calendar Interview Questions Answers

16. How do you add and subtract a day, month, and year in a Date object? (answer)

This is one of the common day to day task of a Java developer, you can use the code shared in the answer for adding or subtracting a day or month from the Date object.

17. How do you compare two dates in Java to check if they are equal? (answer)

This is one of the easier questions you will see in terms of skill checking on Date classes. The java.util.Date class implements the equals() method, which returns true if both Dates are the same and false otherwise.

18. How do you find if one date comes before or after another date in Java? (answer)

This is the follow-up question of the previous question. The interviewer further checks the candidate's date comparison skill by asking this question. The answer is simple, the java.util.Date class provides before() and after() method which returns true and false if the date on which method is called comes before or after the other date passed as a method argument.

19. How do you convert java.util.Date to java.sql.Date in Java JDBC? (answer)

It's the follow-up question of the 6th question. Since java.sql.Date is a subclass of java.util.Date you can simply get the time in a millisecond and passed it to SQL date as shown below:

Date now = new Date();
java.sql.Date sqlDate = new java.sql.Date(now.getTime());

Simple and easy right? but there are some interesting follow-up questions when you write this code, I suggest you check the answer link for more detailed discussion, where I have answered those follow-up questions as well. You can further see Java Fundamentals: The Java Language to learn more about Java fundamental concepts.

 Java Date and Calendar Interview Questions Answers

Btw, you would need a Pluralsight membership to get access to this course, which costs around $29 per month or $299 annually (14% discount).

If you don't have Pluralsight membership, I encourage you to get one because it allows you to access their 5000+ online courses on all the latest topics like front-end and back-end development, machine learning, etc. It also includes interactive quizzes, exercises, and the latest certification material.

It's more like Netflix for Software Developers and Since learning is an important part of our job, Pluralsight membership is a great way to stay ahead of your competition.

They also provide a 10-day free trial without any commitment, which is a great way to not just access this course for free but also to check the quality of courses before joining Pluralsight.

20. How to convert local time to GMT in Java? (answer)

This is similar to one of the previous questions where we need to get the current time in GMT

21. How do you show timezone in formatted dates in Java? (answer)

see the answer link for a code example

22. What is the difference between java.util.Date and java.sql.Date in Java? (answer)

There is much difference between them but the most important one is that java.sql.Date is from the JDBC package and it acts as converted between Date and Time data types in database and Date in Java.

23. How do you calculate the difference between two dates in Java? (program)

There are multiple ways to calculate the difference between two dates in Java e.g. you can get the long millisecond values from two dates and get the difference but that's not very valuable, you mostly need the difference in days or hours, etc. See the program to learn more about those differences.

24 How do you convert a string (YYYYMMDD) to date in Java? (answer)

You can use SimpleDateFormat prior to JDK 8 and DateTimeFormatter along with format and parse method to convert a string to date in Java.

That's all about the date, time, and Calendar based Java Interview Questions. It's very important for a Java developer to have a solid understanding of the Date and Time API of Java, both old and new because you will not find Java 8 in every project you work. You still need to know how to work with old Date and Calendar API while maintaining the legacy project for a couple of more years.

Further Learning
Complete Java Masterclass
Java Fundamentals: The Java Language
Java In-Depth: Become a Complete Java Engineer!

Other Java Interview Questions Articles.
  • Top 10 Spring Framework Interview Questions with Answers (see here)
  • 25 System Design Interview Questions for Programmers (questions)
  • 15 Data Structure and Algorithm Questions from Java Interviews (read here)
  • 20  Java Design Pattern Questions asked on Interviews (see here)
  • 10 frequently asked Servlet Interview Questions with Answers (see here)
  • 20+ binary tree coding problems for Java programmers (questions)
  • Top 10 JSP Questions  from J2EE Interviews (read here)
  • 20+ Array-based coding questions from Interviews (Questions)
  • 12 RESTful Web Services Questions from Interviews (read here)
  • 10 Hibernate Interview Questions for Java EE Developer (see here)
  • 21 String Algorithms problems from Coding interview (questions)
  • 10  JDBC Interview Questions for Java Programmers (questions)
  • 20+ linked list coding problems from interviews (questions)
  • 15 Java NIO and Networking Interview Questions with Answers (see here)
  • Top 10 Trick Java Interview Questions and Answers (see here)
  • Top 40 Core Java Phone Interview Questions with Answers (list)
  • 50+ Data Structure and Algorithm Interview Questions (data structure)
  • 20+ String-based Coding Problems from Interviews (questions)

Thanks for reading this article so far. If you like these questions then please share with your friends and colleagues too. If you have any questions or feedback then please drop a note.

P. S. - If you are looking to fill gaps in your Java knowledge or want to learn Java from scratch, here are some useful free online Java courses to check out at your convenience, they are good for online learning from your office or home.

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.