• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Format Date using Calendar

 
Erik Pragt
Ranch Hand
Posts: 125
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1510
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Erik Pragt
Ranch Hand
Posts: 125
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic