Alfred’s Computing Weblog

Alfred Java-cored Computing Weblog

Posts Tagged ‘date

Plays with Java Date/Time

leave a comment »

How to set a Date?
We can make use of GregorianCalender package: “java.util.GregorianCalendar
The GregorianCalendar provide 3 useful constructor to set date.

// Set the day (Year, Month, Day)
Calendar firstJanTwoThousandEight = new GregorianCalendar(2008, 0, 1);
// Set the day (Year, Month, Day, Hour, Min)
Calendar firstJanTwoThousandEightSevenAmTwentySevenMin = new GregorianCalendar(2008, 0, 1, 7, 27);
// Set the day (Year, Month, Day, Hour, Min, Secs)
Calendar firstJanTwoThousandEightSevenPmTwentySevenMinFiftyEightSecs = new GregorianCalendar(2008, 0, 1, 19, 27, 58);

More details, pls refer GregorianCalendar API

How to adjust date?
Here is going to guide on setting date like “One day before today”, “An hour later” and “A month after today”.
The package that provide such functionality is the very simple / root java package — java.util.Calendar

// initialize a calendar object
Calendar calendar = Calendar.getInstance();

// set the calendar time (here, we set it to "today" / "now" date)
calendar.setTime(new Date());
System.out.println("Today [" + sdf.format(calendar.getTime()) +"]"); 
/* $> Today [2008-04-30 11:04:14.750] */

// adjustment of date is happen here
// adjust to a day before
calendar.add(Calendar.DAY_OF_YEAR, -1);
System.out.println("Yesterday [" + sdf.format(calendar.getTime()) +"]"); 
/* $> Yesterday [2008-04-29 11:04:14.750] */

// adjust to a month after today
calendar.add(Calendar.MONTH, 1);
System.out.println("A month after today [" + sdf.format(calendar.getTime()) +"]"); 
/* $>  A month after today [2008-05-30 11:04:14.750] */

// adjust to an hour later
calendar.add(Calendar.HOUR_OF_DAY, 1);
System.out.println("An hour later [" + sdf.format(calendar.getTime()) +"]"); 
/* $> An hour later [2008-04-30 12:04:14.750] */

More details, pls refer Calendar API

Advertisements

Written by Alfred

April 30, 2008 at 12:33

Posted in Java

Tagged with