-
Simple Date Format
I need some help understanding the SimpleDateFormat class. I really don't get it when it comes to this class. Have a look at this code:
Code:
import java.awt.*;
import java.applet.*;
import java.util.*;
import java.text.*;
public class Clock4 extends Applet implements Runnable{
Label lblShort = new Label();
Label lblMedium = new Label();
Label lblLong = new Label();
Label lblHuge = new Label();
Thread looper;
SimpleDateFormat formatter = new SimpleDateFormat("hh:mm:ss");
public void init(){
setFont (new Font ("SansSerif", Font.PLAIN, 14));
setLayout(new GridLayout(0,2));
add (new Label("h:mm:ss"));
add (lblShort);
add (new Label("EEE, MMM d, ''yy"));
add (lblMedium);
add (new Label("hh 'o''clock' a, zzzz"));
add (lblLong);
add (new Label("yyyyy.MMMMM.dd GGG hh:mm aaa"));
add (lblHuge);
} // end init
public void start(){
if (looper == null){
looper = new Thread(this);
looper.start();
} // end if
} // end start
public void stop(){
looper = null;
} // end stop
public void run(){
while (true){
Date currentTime = new Date();
formatter.applyPattern("h:mm:ss");
lblShort.setText(formatter.format(currentTime));
formatter.applyPattern("EEE, MMM d, ''yy");
lblMedium.setText(formatter.format(currentTime));
formatter.applyPattern("hh 'o''clock' a, zzzz");
lblLong.setText(formatter.format(currentTime));
formatter.applyPattern("yyyyy.MMMMM.dd GGG hh:mm aaa");
lblHuge.setText(formatter.format(currentTime));
} // end while
} // end run
} // end class def
The following snippets of code:
Code:
formatter.applyPattern("h:mm:ss");
lblShort.setText(formatter.format(currentTime));
I don't understand how the applyPattern method carries over to the other line. Its the other line that outputs the new format to the label. How is that working? Is the applyPattern("h:mm:ss") stored in the formatter reference and so then applied to the date object "currentTime"? I don't understand how a pattern is defined when the SimpleDateFormat reference was instantiated and then another pattern can be applied using the applyPattern method using the object "formatter"? Can someone explain how this works or point me to a site that does. The API does not help at all.
-
In simple words, SimpleDateFormat class have overloaded method name applyPattern(). It convert the string pattern in to date format. Best thing is look at the SimpleDateFormat class. Are you working on any IDE? If so you can simply look at those overloaded methods and how they translate in to date format.