• Post Reply Bookmark Topic Watch Topic
  • New Topic

Output of time  RSS feed

 
Peter C. Sandgaard
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I have been dealing a bit with formatting and I have a little thing that puzzles me about printing a time. I have the following code:

import java.util.*;


public class TestFormats {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

// Create an object of date
Date today = new Date();

// Get the exact time now
String.format("%tr", today);
// Print the time now (and only the time e.g. 12:12:00 PM)
System.out.println(today);

}

}

According to the book "Head first Java" page 301, it should print the time alone like this:

12:12:00 PM

but....

It prints out the whole date and time like this:

Mon Jan 12 19:44:21 CET 2009

Why is that ?
 
Olivier Legat
Ranch Hand
Posts: 176
Chrome Mac Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Peter and Welcome to Javaranch.

Firstly, place your code between UBB tabs to make it easier to read. To do this select your code whilst editing and press the Code button to get something as such:



You're mistake seems to be where you put String.format("%tr", today). The method is returning a value but you aren't storing it anywhere so you lose it. You are printing the date when you type "today" instead of the time because you aren't saving to the time before printing it. Try this.



Note that the method String.format(String, Object) doesn't change the format of the Date. It simply reads the date makes a "copy" of it in a different format.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!