Calendar/Date in Java
We dive into the difference between the date and calendar objects in Java and explain how to use each of these objects in your code.
Join the DZone community and get the full member experience.Join For Free
Hey everyone! I'm new here and I still don't know what this community finds useful. I would like to discuss the Calendar and Date objects for those who are beginning their Java journey. I hope this helps!
What Is the Difference Between Date and Calendar?
Date- amount of milliseconds, starting from 01.01.1970.
Calendar- work with a usual date.
Which One Is Better to Use?
I can't say which way is better, but I prefer Calendar to Date, as it is richer in functions.
1. Coding Calendar
Making the Calendar Object
Calendar calendar = GregorianCalendar.getInstance();
Setting the Value of Our Calendar Object
calendar.set(... , ...);
The first parameter can be
Calendar.DAY_OF_MONTH and so on.
The second value is your variable. You can set parameters with it, and, you guessed it, it is numeric.
There are other values we can use, but they are all pretty similar to each other, so I think
calendar.add is the only one we need to use.
So, our code should now look like this:
Change your parameters by adding some value.
2. Coding Date
Making an Object
Date date = new Date();
Get the Date From the Calendar
long millis = date.getTime();
Yes, we use
long to describe time in our Date (milliseconds).
System.out.println("Date in type CALENDAR:" + calendar.getTime());
System.out.println("Date in type DATE:" + String.valueOf(millis));
Don't forget that to display/write you need to convert your value into a string.
There are different ways to change your format (the way it displays value).
First Way - Formatter
Make an Object
Formatter formatter = new Formatter();
Set the Pattern
formatter.format("%t.. %t.., %t..",object for % 1,object for % 2,object for % 3);
Here is a useful link with a table of patterns: Formatter
It is used with type
System.out.println("FORMATTER date" + formatter);
Second Way - SimpleDateFormat
Make an Object
SimpleDateFormat dateFormat = new SimpleDateFormat("pattern");
Table with patterns: SimpleDateFormat.
Here we also work with type
System.out.println("SIMPLEDATEFORMAT date" + dateFormat.format(date));
- If you want to change your Formatter pattern or SimpleDateFormat pattern, make another object. If you change the existing object, you will catch a mistake.
- Always check the
Calendartype for the right values (month < 13 and so on).
- Set to set, get to get something from Calendar.
Hopefully, this was useful for you! If you have any questions, write to me anytime. If you think that you need something more deeply, check my articles here.
Published at DZone with permission of Yuri Filatov. See the original article here.
Opinions expressed by DZone contributors are their own.