Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

A kinder, gentler java.util.Date?

 
Garann Means
Ranch Hand
Posts: 214
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I'm wondering if there's a simpler way to return the current date and time from the system than what I'm doing right now. I'm really hoping there's something analogous to the "Date()" I was using when I was writing ASP. This is my code:

I want the date and time to appear in a friendly format (not milliseconds since jan 1, 1970, or whatever it is). It seems like that would be a common need, and there would be a quick way to address it. Am I missing something?
Thanks,
g.
 
Cindy Glass
"The Hood"
Sheriff
Posts: 8521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Perhaps you are looking for something like SimpleDateFormat.
Try playing with this:

[ February 05, 2002: Message edited by: Cindy Glass ]
 
Garann Means
Ranch Hand
Posts: 214
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Cindy,
Thanks for the quick reply.
What I'm looking for is a way to get around needing both a Date and a DateFormatter. I've been to everything I could think of in the API, but I can't find a method in the Date class that returns anyting but the entire date/time in a String (no good, because I need to display the two in different table cells) or integers representing the seperate elements of the date.
It just seemed like there would be a shortcut for such a common operation.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try

With no arguments, the Date() constructor uses the current system time. And the toString() method will give you a reasonably nice display, depending on your locale and system. On my system, I get

If you don't like the format you get, then yes you will need to use some sort of DateFormat to fix it - but chances are good you won't have to.
[ February 05, 2002: Message edited by: Jim Yingst ]
 
Garann Means
Ranch Hand
Posts: 214
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you both.
I ended up just using Jakarta's datetime tag library, since I wanted something neat and clean to place on multiple pages.
But I have another question: how do you get the difference between two dates? I need to get someone's current age. I try subtracting, and it gives me a conversion error. The Date.compareTo() method gives me integers I assume represent greater than, less than, or equal to. How can I get the time difference, rounded to years?
..Nevermind. I just subtracted getYear() from getYear(). Thanks again.
g.
[ February 05, 2002: Message edited by: Garann Rose Means ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic