Java Reference
In-Depth Information
This time, your program says hello to you.
Congratulations. At this point, you've created a program that does the basic things all programs do:
accepts input, modifies the input to accomplish something, and produces output. It might not seem like
much, but it's the first step on a fun path. We do much more before we're done.
Further Development
Just for fun, let's tack on a bit more functionality. When programs generate console output, they often
include the date and time. Formatting a date takes more code than most people would expect until
they've had to do it. That's because the real world has so many different date formats. In the United
States, month/day/year (MDY) format prevails. In Europe, day/month/year (DMY) prevails. In addition
to the date formats used by people, computer systems also have various ways of representing dates,
from simple variations such as year/month/day (YMD) to far more arcane arrangements. Java, having
inherited from C, uses the same date storage technique as C and Unix (which was originally coded
mostly in C) and Linux (which shares much with Unix). Consequently, Java stores dates as the number of
seconds since January 1, 1970. In more detailed and technical terms, Java's “epoch” started at January 1,
1970, 00:00:00 GMT.
So, how do we turn the number of seconds since 1970 into a nicely formatted time stamp for our
output? Listing 1-4 shows one way. (Part of both the joy and the pain of software development is that
there's almost always more than one way to do something.) I explain more about the new pieces of code
in the next section.
Listing 1-4: Adding a timestamp to Hello
package com.apress.java7forabsolutebeginners;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Hello {
public static void main(String[] args) {
// First, get the date as seconds since 1/1/1970
// Note that a Date object also contains time information
Date now = new Date();
// Second, create a formatter object
SimpleDateFormat formatter =
new SimpleDateFormat("EEE, MMM dd, yyyy HH:mm:ss");
// Third, apply the formatter to the date
String formattedDate = formatter.format(now);
// Finally, add our formatted date to our output
System.out.println(formattedDate + "> Hello, " + args[0] + "!");
}
}
When you run this program, you'll see a date and time stamp before your other output.
Search WWH ::




Custom Search