How do I print out current date and time in Java?

Discussion in 'Mac Programming' started by iSamurai, Sep 28, 2008.

  1. macrumors 65816

    iSamurai

    Joined:
    Nov 9, 2007
    Location:
    ɹǝpun uʍop 'ǝuɐqsı&#
    #1
    Hello,

    Can someone please help me with printing out the current date and time. It just has to be a simple, one line, date/time in JOptionPane.

    I'd like to see the entire java file -- from the import xxx, to the JOptionPane.showMessageDialog line...

    Thank you.
     
  2. Wes
    macrumors 68020

    Wes

    Joined:
    Jun 22, 2001
    Location:
    London
    #2
    Code:
    import java.util.Date;
    import javax.swing.JOptionPane;
    
    
    public class DateTime {
    
    	public static void main(String[] args) {
    		JOptionPane.showMessageDialog(null, new Date());
    
    	}
    
    }
    
    This is relying on the toString() method of the Date class. Declaring a new Date object with no parameters creates a Date instance with the current date/time.

    The null in the call is there as the method optionally takes the parent component of this dialog box.
     
  3. thread starter macrumors 65816

    iSamurai

    Joined:
    Nov 9, 2007
    Location:
    ɹǝpun uʍop 'ǝuɐqsı&#
  4. macrumors 6502a

    Joined:
    Jan 15, 2007
    #4
    Just to expound upon what Wes said, you might want to check out the SimpleDateFormatter class if don't like the default format, pretty easy to use and very handy.
     

Share This Page