GeeCON Prague 2014*
The moose likes Servlets and the fly likes Format Date using Calendar Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Servlets
Bookmark "Format Date using Calendar" Watch "Format Date using Calendar" New topic
Author

Format Date using Calendar

Erik Pragt
Ranch Hand

Joined: Sep 08, 2001
Posts: 125
Hello everyone (again),
I have another question:
How do I format my Calendar Object in the following String: 010908.gif (so the last two digits of the year, then a month with a zero, and then a day with a zero...something like 'yyMMDD'
I know how to do it using the Date Object:
SimpleDateFormat formatter = new SimpleDateFormat ("yyMMDD");
Date currentTime_1 = new Date();
String dateString = formatter.format(currentTime_1);
but how to do this using a Calendar rather than a Date object??
Thanks in advance,
Erik Pragt
The Netherlands
Bosun Bello
Ranch Hand

Joined: Nov 06, 2000
Posts: 1510
What about...
GregorianCalendar gc = new GregorianCalendar()
You can then retrieve the date or time object.
Date now = cal.getTime()

Check the API for the other methods.

Bosun

Bosun (SCJP, SCWCD)
So much trouble in the world -- Bob Marley
Erik Pragt
Ranch Hand

Joined: Sep 08, 2001
Posts: 125
I don't think I get it... you are still using a Date object? And what is this 'cal' object??? (Is it Calendar cal = Calendar.getInstance() or something???)
Thanks for your help so far,
Erik
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
The Calendar class has a getTime method that returns a Date object with the same timestamp as the Calendar object.
One option for formatting the date of a Calendar object, is to
use code such as the following:
Calendar cal = {obtain reference to your calendar object};
SimpleDateFormat formatter = new SimpleDateFormat ("yyMMDD");
String dateString = formatter.format(cal.getTime());
Basically, you use the Data formatting classes by "converting" the Calendar into a Date object via the getTime() method.
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
If all you want to do is format the current time, there is no reason to use the Calendar class at all. Your code example using just the Date object is fine. If you are trying to format a Calendar object containing an arbitrary time, then you can use the Calendar class's getTime() method to "convert" the Calendar into a Date object.
BTW, why is this in the Servlet board? It should be on one of the Java beginner boards.
 
 
subject: Format Date using Calendar