Here I would like to discuss about such objects as Calendar or Date with those, who begin their way in Java.
What is the difference in Date and Calendar?
Date - amount of milliseconds, starting from 01.01.1970
Calendar - work with a usual date
What is better to use?
We can't say which way is better, but I prefer Calendar to Date as it is richer in functions and usual for us.
*1. Coding Calendar
Calendar calendar = GregorianCalendar.getInstance();
Set the value of your object
calendar.set(... , ...);
The first parameter can be Calendar.MONTH, Calendar.YEAR, Calendar.DAYOFMONTH and so on, like what you set.
The second value is your variable, you set parameter with, and, as you guess, it is numeric
You can also use others, but they are similar to each other, so I think only calendar.add is needed.
Change your parameters by adding some value.
*2. Coding Date
Date date = new Date();
How to get the date from Calendar?
How to get milliseconds?
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 into string your value.
There are different ways to change your format (the way it displays value).
1st - Formatter.
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 Date.
System.out.println("FORMATTER date" + formatter);
2nd - SimpleDateFormat:
SimpleDateFormat dateFormat = new SimpleDateFormat("pattern");
Table with patterns: SimpleDateFormat
Here we also work with type Date
System.out.println("SIMPLEDATEFORMAT date" + dateFormat.format(date));
• If you want to change you Formatter pattern or SimpleDateFormat pattern, make another one object. If you change the existing object, you will catch a mistake.
• Always check the Calendar type for the right values (month <13 and so on)
• Set to set, get to get something from Calendar
Hopefully, it was useful for you and understandable! If you have any questions, write me anytime.
Good luck in your job!