Skip to main content

Assignment #2a

 

DateTime

filenames: DateTime.java, DateTime.class

Create the text-based application DateTime.java. This program should instantiate a Date object, then use that object's toString() method to display the current date and time to “Standard Out”. Be sure to upload your platform-independent source code to your mislab account public_html directory, and be sure to actually test your program on your mislab account.

1. Use Eclipse or a text editor to create a project named DateTime. (The instructions here assume that you are using Eclipse, but you can certainly type your program using a text editor.)

2. Within your project, create a class named DateTime. This class file should contain:

- a class header

- a main method header

- a statement to instantiate a Date object

Instantiating a Date object (an instance of the Date class) in Java is exactly like instantiating one in Javascript. Use the “new” operator. Since Java is a strongly typed language, you must define your variable first, such as:

Date myDate;
myDate=new Date();

This defines a variable named myDate, whose data type is Date (it is a Date object). It then uses the “new” operator to instantiate a Date object, and assigns that object to the variable myDate.

- a statement to call your Date object's toString() method to get a string representation of the Date object (and assign that string to a String variable)

String dateString;
dateString=myDate.toString();

- a statement to display the string

System.out.println(dateString);

4. You will notice that you have syntax errors – unresolved references – because the Date class is not in a standard package that is automatically available to your program.

 Before your class header, import the classes from the java.util package:

import java.util.*;

5. Run your program. As a side-effect, this will also create your .class file. Hopefully it will display the correct date and time on the Console.

6. Upload your DateTime.java file from this project to your mislab account. The file will be in the src subdirectory, under your project folder in your designated workspace. In your ftp program, drag just DateTime.java from the left (your computer) to your mislab public_html directory.

7. ssh to mislab, log in, move to your public_html directory, compile your program, and run your program to make sure it works.

 cd public_html

 javac DateTime.java

 java DateTime