jQuery in Action, 3rd edition
The moose likes Beginning Java and the fly likes Getting current date Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Getting current date" Watch "Getting current date" New topic

Getting current date

Jennifer Sohl
Ranch Hand

Joined: Feb 28, 2001
Posts: 455
Hi. I am trying to figure out how to retrieve the current system date and display it as a JLabel.
I've looked at the API's for Calendar,DateFormat, and SimpleDateFormat, but I am still very confused. I don't really understand how these classes work. I'm not sure which one of these I should be using. Suns docs do not have any examples that helped me out any. (It was a lot easier in RPG when I could just code 'SYSDAT' and voila!)
Any help would be greatly appreciated!
Thanks a bunch
Mike Curwen
Ranch Hand

Joined: Feb 20, 2001
Posts: 3695

Read the API for the Calendar class a bit closer.

(for jdk 1.3.1)... the third paragraph shows you how to obtain a GregorianCalendar object with the current date and time.

Then look in the GregorianCalendar API, there is a HUGE code listing, showing you how to obtain any part of that date.

If that all seems like way to much work... there is a 'quick and dirty' way of obtaining the current date and time.

It involves the java.util.Date class. Check the API, and read what it says for the constructor.
(it says it makes a Date object with the current system time). Then look at its toString() method. It says that it converts the Date object to a formatted String.

If this format is unacceptable, then you would use this Date object in combination with a SimpleDateFormat object, to convert it into whatever format you want.

I admit the formatter is a bit confusing, so here is an example:In this example, d is a java.util.Date object. In the API for SimpleDateFormat, it explains what all the dd MMM yyyy, etc... means.
[ February 20, 2002: Message edited by: Mike Curwen ]
Dean Reedy
Ranch Hand

Joined: Sep 10, 2001
Posts: 89
Here is one way:
import java.util.*;
import java.text.*;
public class DateTest1 {
static public void DisplayDate() {
Date today;
String result;
SimpleDateFormat formatter;
formatter = new SimpleDateFormat("MM/dd/yyyy");
today = new Date();
result = formatter.format(today);
static public void main(String[] args) {
Note: There is a calander class for this as well, but here is what I understood you wanted.
Erik Dark
Ranch Hand

Joined: Jan 28, 2002
Posts: 107
This may be a start:

Also take a look at the System class' methods (e.g getProperty)
Erik Dark
[ February 20, 2002: Message edited by: Erik Dark ]
Jennifer Sohl
Ranch Hand

Joined: Feb 28, 2001
Posts: 455
Thanks for all your help.
All of you guys are great!!
I agree. Here's the link: http://aspose.com/file-tools
subject: Getting current date
It's not a secret anymore!