DEV Community

Yuri Filatov
Yuri Filatov

Posted on • Updated on • Originally published at andersenlab.com

Calendar / date in java

Here I would like to discuss about such objects as Calendar or Date with those, who beggin 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
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.

*2. Coding Date
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)

*3. Display

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.

*4. Format
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));

*5. Tips

  • 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 understable! If you have any questions, write me anytime.

Good luck in your job!

Top comments (0)