Recipe 6.4 Converting YMDHMS to a Calendar or Epoch Seconds


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


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 still confusing.

//  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 EDT 1986 It is now Thu Mar 25 16:36:07 EST 2004 It is now Thu Mar 25 16:36:07 EST 2004 D3 set to Mon Apr 12 16:36:07 EST 1915

Java Cookbook
Java Cookbook, Second Edition
ISBN: 0596007019
EAN: 2147483647
Year: 2003
Pages: 409
Authors: Ian F Darwin

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: