Here I would like to discuss about such objects as Calendar or Date with those, who begin their way in Java.
Date – amount of milliseconds, starting from 01.01.1970
Calendar – work with a usual date
We can’t say which way is better, but I prefer Calendar to Date as it is richer in functions and usual for us.
Making object
`Calendar calendar = GregorianCalendar.getInstance();
Set the value of your object
`calendar.set(… , …);
The first parameter can be Calendar.MONTH, Calendar.YEAR, Calendar.DAY_OF_MONTH 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.
`calendar.add(parameter,value);
Change your parameters by adding some value.
Making object
`Date date = new Date();
How to get the date from Calendar?
“`
date=calendar.getTime();
How to get milliseconds?
long millis = date.getTime();
Yes, we use long to describe time in our Date (milliseconds)
Calendar:
`System.out.println(“Date in type CALENDAR:” + calendar.getTime());
Date:
`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.
Make 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 Date.
Display
`System.out.println(“FORMATTER date” + formatter);
2nd – SimpleDateFormat:
Make object
`SimpleDateFormat dateFormat = new SimpleDateFormat(“pattern”);
Table with patterns: [SimpleDateFormat
Here we also work with type Date
Display
`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!
written by Andersen