Monday 7 April 2014

Convert time stamp to Date Format

Usually time stamp is a long value. Date class is used to convert the time stamp to a meaning full value.
   Date day = new Date(timeStamp);
Here timeStamp must be a String variable. Date Constructor takes the time stamp as an argument to it and convert it to Date format.


import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.Date;

public class TimeStampEx{
 JTextArea displayArea;
 JFrame frame1;
  
 TimeStampEx(){
  JButton click = new JButton("Click Me");
  
  /* Initialize Display Area */
  displayArea = new JTextArea();
  displayArea.setEditable(false);
  JScrollPane scrollPane = new JScrollPane(displayArea);
  scrollPane.setPreferredSize(new Dimension(450, 150));
   
  /* Initialize Frame */
  frame1 =new JFrame("Sample Frame");
  frame1.pack();
  frame1.setVisible(true);
  frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame1.getContentPane().add(click, BorderLayout.PAGE_START);
  frame1.getContentPane().add(scrollPane, BorderLayout.CENTER);
  frame1.setSize(300, 300);
    
  click.addActionListener(new ActionListener(){
   public void actionPerformed(ActionEvent e){
    /* Get the Time Stamp when the Action Occurs */
    long timeStamp= e.getWhen();
    Date day = new Date(Long.parseLong(""+timeStamp));
    displayArea.append("You clicked at " + day+"\n");
   } 
  }); 
 }
 
 public static void main(String args[]){
  new TimeStampEx();
 }
}

Output
 
Click the button and observe the result in the text area.








Previous                                                    Next                                                    Home

No comments:

Post a Comment