Java Date and Calendar examples
This tutorial shows you how to work with java.util.Date
and java.util.Calendar
.
1. Java Date Examples
Few examples to work with Date
APIs.
Example 1.1 – Convert Date to String.
SimpleDateFormat sdf = new SimpleDateFormat("dd/M/yyyy");
String date = sdf.format(new Date());
System.out.println(date); //15/10/2013
Example 1.2 – Convert String to Date.
SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
String dateInString = "31-08-1982 10:20:56";
Date date = sdf.parse(dateInString);
System.out.println(date); //Tue Aug 31 10:20:56 SGT 1982
P.S Refer to this – SimpleDateFormat JavaDoc for detail date and time patterns.
Example 1.3 – Get current date time
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date)); //2013/10/15 16:16:39
Example 1.4 – Convert Calendar to Date
Calendar calendar = Calendar.getInstance();
Date date = calendar.getTime();
2. Java Calendar Examples
Few examples to work with Calendar
APIs.
Example 2.1 – Get current date time
SimpleDateFormat sdf = new SimpleDateFormat("yyyy MMM dd HH:mm:ss");
Calendar calendar = new GregorianCalendar(2013,0,31);
System.out.println(sdf.format(calendar.getTime()));
Output
2013 Jan 31 00:00:00
Example 2.2 – Simple Calendar example
SimpleDateFormat sdf = new SimpleDateFormat("yyyy MMM dd HH:mm:ss");
Calendar calendar = new GregorianCalendar(2013,1,28,13,24,56);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH); // Jan = 0, dec = 11
int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
int weekOfYear = calendar.get(Calendar.WEEK_OF_YEAR);
int weekOfMonth= calendar.get(Calendar.WEEK_OF_MONTH);
int hour = calendar.get(Calendar.HOUR); // 12 hour clock
int hourOfDay = calendar.get(Calendar.HOUR_OF_DAY); // 24 hour clock
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
int millisecond= calendar.get(Calendar.MILLISECOND);
System.out.println(sdf.format(calendar.getTime()));
System.out.println("year \t\t: " + year);
System.out.println("month \t\t: " + month);
System.out.println("dayOfMonth \t: " + dayOfMonth);
System.out.println("dayOfWeek \t: " + dayOfWeek);
System.out.println("weekOfYear \t: " + weekOfYear);
System.out.println("weekOfMonth \t: " + weekOfMonth);
System.out.println("hour \t\t: " + hour);
System.out.println("hourOfDay \t: " + hourOfDay);
System.out.println("minute \t\t: " + minute);
System.out.println("second \t\t: " + second);
System.out.println("millisecond \t: " + millisecond);
Output
2013 Feb 28 13:24:56
year : 2013
month : 1
dayOfMonth : 28
dayOfWeek : 5
weekOfYear : 9
weekOfMonth : 5
hour : 1
hourOfDay : 13
minute : 24
second : 56
millisecond : 0
Example 2.3 – Set a date manually.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy MMM dd HH:mm:ss");
Calendar calendar = new GregorianCalendar(2013,1,28,13,24,56);
System.out.println("#1. " + sdf.format(calendar.getTime()));
//update a date
calendar.set(Calendar.YEAR, 2014);
calendar.set(Calendar.MONTH, 11);
calendar.set(Calendar.MINUTE, 33);
System.out.println("#2. " + sdf.format(calendar.getTime()));
Output
#1. 2013 Feb 28 13:24:56
#2. 2014 Dec 28 13:33:56
Example 2.4– Add or subtract from a date.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy MMM dd");
Calendar calendar = new GregorianCalendar(2013,10,28);
System.out.println("Date : " + sdf.format(calendar.getTime()));
//add one month
calendar.add(Calendar.MONTH, 1);
System.out.println("Date : " + sdf.format(calendar.getTime()));
//subtract 10 days
calendar.add(Calendar.DAY_OF_MONTH, -10);
System.out.println("Date : " + sdf.format(calendar.getTime()));
Output
Date : 2013 Nov 28
Date : 2013 Dec 28
Date : 2013 Dec 18
Example 2.5– Convert Date to Calendar.
SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
String dateInString = "22-01-2015 10:20:56";
Date date = sdf.parse(dateInString);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
Nice Blog!
For Calendar creation is better to use the existing constants for the Month to avoid the Tipycal error due to the fact that Calendar uses
0 -> January
1 – > Feberuary
…
11 -> December
So
Calendar calendar = new GregorianCalendar(2013, Calendar.NOVEMBER, 28);
is prefered over
Calendar calendar = new GregorianCalendar(2013, 10, 28);
One question about weeks and years :
I tried to use this :
private SimpleDateFormat wwyyyy = new SimpleDateFormat(“wwyyyy”);
But this fails terribly for dates late in the year that belongs to the first week of next year…
e.g 29-31. 12 2014 belongs to week 01 in 2015, but the date-format gives “012014”…
What do you do to get the correct week/year-combination for this years three last days ?
Actually I found the answer on another page.
When using weeks with years, I should use
private SimpleDateFormat wwyyyy = new SimpleDateFormat(“wwYYYY”); in order to get the correct year for the week…
nice tutorial, really helpful.. thanks….
best site to learn java.
I like this
best site to learn java.
Thank You!
HOW CAN I WRITE PROGRAM TO FIND DAY USING SPRING MVC
Hola a todos alguíen me auida con este ejercicio de java en netbeans.
Es tracta de fer un programa en Java que demani una data i mostri per pantalla el dia següent. És a dir, el programa demanarà tres enters (un dia, un mes i un any) i mostrarà quin és el dia següent en el mateix format (dia, mes i any). El programa ha de filtrar que el valor introduït pel dia estigui entre 1 i 31 i que el valor introduït pel mes estigui entre 1 i 12. Podeu suposar que la data introduïda és real (és correcta). Es tracta de sumar 1 dia a la informació donada tenint present les següents característiques:
Hay meses que tienen 31 días.
Hay meses que tienen 30 días.
Febrero tiene 28 días salvo si el año es bisiesto ( ” bisiesto ” ) , en este caso tiene 29 días. Se considera año bisiesto aquel que es múltiple de 4, pero no es divisible por 100, a menos que lo sea también para 400 .
El programa debe estar convenientemente documentado.
Ejemplos de funcionamiento :
Entrada : 1 2 2014
Salida : 2 2 2014
Entrada : 31 1 2014
Salida : 1 2 2015
Entrada : 28 2 2 015
Salida : 1 3 2015
Entrada : 28 2 2000
Salida : 29 2 2000
Entrada : 30 11 1972
Salida : 1 12 1972
I need to read a log file which contains one day data. Now I need to parse only the last hours data, whatever the last time may be in the log file… I have written a code which will read from the last line of the file..
paths = f1.listFiles();
for(File path:paths) {
ReversedLinesFileReader reverse= new ReversedLinesFileReader(path);
String line;
while ((line = reverse.readLine()) != null) {
// process the line.
if(line.contains(Constants.INFO)){
System.out.println(“line contains INFO”);
}
}
Now I need to parse only last one hour data. My last two lines of the log file looks like this.
INFO: May 30 23:59:59 Ignoring load report from EX8103 for DT5243 as it is not assigned to a loading tool.
INFO: May 30 23:59:59 Assignment succeeded: Sat May 31 00:00:01 WST 2014: SUCCESS DT4206
Calendar rightNow1Hour = Calendar.getInstance();
rightNow1Hour.set(Calendar.HOUR, rightNow1Hour.get(Calendar.HOUR)-1);
System.out.println(“1hourB4now .\t:-” + rightNow1Hour.getTime());
I have one doubt.
Giving just M dont work for me as in if month is Nov i give MMM and for Sept, i have to give MMMM .how can i work this out for any given month…
It’s a late response but it may be helpful to some!
SimpleDateFormat sdf = new SimpleDateFormat(“yyyy MMM dd HH:mm:ss”);
Calendar calendar = new GregorianCalendar(2013,0,31);
if(calendar.get(Calendar.MONTH) == 8 /* September */ ) {
sdf = new SimpleDateFormat(“yyyy MMMM dd HH:mm:ss”);}System.out.println(sdf.format(calendar.getTime()));
Hello,
I would propose to use always DateFormat with setLenient(false) setting. Othwerwise unexpected errors might occur.
SimpleDateFormat sdf = new SimpleDateFormat(“dd-M-yyyy hh:mm:ss”);
sdf.setLenient(false);
String dateInString = “01-13-1982 10:20:56”;
Without calling setLenient(false) the date string would be interpreted as “Sat Jan 01 10:20:56 CET 1983”.
cheers
pls explam in how to calculate date to day using calender