O'Reilly logo

Java Cookbook by Ian F. Darwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Converting YMDHMS to a Calendar or Epoch Seconds

Problem

You have year, month, day, hour, minute, and maybe even seconds, and you need to convert it to a Calendar or a Date.

Solution

Use the Calendar class’s set(y,m,d,h,m[,s]) method, which allows you to set the date/time fields to whatever you wish. Note that when using this form and providing your own numbers or when constructing either a Date or a GregorianCalendar object, the month value is zero-based while all the other values are true-origin. Presumably, this is to allow you to print the month name from an array without having to remember to subtract one, but it is confusing.

// GregCalDemo.java 
GregorianCalendar d1 = new GregorianCalendar(1986, 04, 05); // May 5 
GregorianCalendar d2 = new GregorianCalendar(  );    // today 
Calendar d3 = Calendar.getInstance(  );    // today 
 
System.out.println("It was then " + d1.getTime(  )); 
System.out.println("It is now " + d2.getTime(  )); 
System.out.println("It is now " + d3.getTime(  )); 
d3.set(Calendar.YEAR, 1915); 
d3.set(Calendar.MONTH, Calendar.APRIL); 
d3.set(Calendar.DAY_OF_MONTH, 12); 
System.out.println("D3 set to " + d3.getTime(  ));

This prints the dates as shown:

It was then Mon May 05 00:00:00 PDT 1986 
It is now Sun Jul 18 22:51:47 PDT 1999 
It is now Sun Jul 18 22:51:47 PDT 1999 
D3 set to Mon Apr 12 22:51:47 PDT 1915

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required