• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Output of time

 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ?
 
Ranch Hand
Posts: 176
Mac Chrome Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic