Skip to Main Content
Java Cookbook
book

Java Cookbook

by Ian F. Darwin
June 2001
Intermediate to advanced content levelIntermediate to advanced
888 pages
21h 1m
English
O'Reilly Media, Inc.
Content preview from Java Cookbook

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
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Practical Cloud-Native Java Development with MicroProfile

Practical Cloud-Native Java Development with MicroProfile

Emily Jiang, Andrew McCright, John Alcorn, David Chan, Alasdair Nottingham
Distributed Computing in Java 9

Distributed Computing in Java 9

Raja Malleswara Rao Malleswara Rao Pattamsetti

Publisher Resources

ISBN: 0596001703Supplemental ContentCatalog PageErrata