NGÀY THÁNG VÀ THỜI GIAN

Khi cần định dạng ngày tháng và thời gian thì chúng ta phải quan tâm đến bốn vấn đề chính phụ thuộc vào từng khu vực trên thế giới.

  • Tên của các tháng trong năm, tên của ngày trong tuần theo từng ngôn ngữ.
  • Thứ tự viết ngày, tháng, năm.
  • Lịch Gregorian có phù họp với khu vực của người sử dụng hay không.
  • Múi giờ của mỗi vùng.

Rất may là lớp DateFormat nhận xử lý tất cả những vấn đề nêu trên. Việc sử dụng nó cũng rất giống như NumberFormat. Trước tiên, ta cần xác định đối tượng khu vực của máy tính. Ta có thể sử dụng đối tượng mặc định hoặc thông qua getAvailableLocales () để nhận được danh sách các đối tượng khu vực mà NumberFormat hỗ trợ. Sau đó gọi một trong ba phương thức sau:

fmt= DateFormat.getDatelnstance(dateStyle, loc);

fmt= DateFormat.getTimelnstance(tìmeStyle, loc);

fmt = DateFonrat. getDeteTimelnstanoe (dateStyle, times ty le, loc) ;

Trong đó dateStyle,          times tyle có thể là một trong các hằng sau

DateFocmat.DEFAULT, DateFormat.FULL, DateFormat.LCNG, DateFormat.MEDIUM, DateFormat. SHORT, còn lọc là đối tượng khu vực.

Ta có thể sử dụng phương thức parse 0 của NumberFormat để phân tích Date và Time. Ví dụ, việc nhập vào ngày tháng và chuyển đổi sang dạng qui định của máy mặc định được thực hiện như sau.

TextField inputField;

DateFormat fmt = NumberFormat.getDateInstance(DateFormat.MEDIUM);

Date input = fmt.parse (inputFiled. getText (). trim ()) ;

Nếu dữ liệu nhập vào không tương thích thì sẽ phát sinh ngoại lệ thuộc loại ParseException

Ví dụ, nếu format nhập là MEDIUM theo qui ước cùa ĩvĩỹ thì dữ liệu ngày thảng nhập vào phải có dạng Sep 18,2005

Nếu người sử dụng nhập vào Sep 18 2005 không có dấu y giữa ngày và năm, hoặc dạng 18/9/2005 thì chương trinh sẽ phát sính lỗi.

Cờ lenient báo cho chương trình thông dịch chình lại ngày tháng cho phù hợp với lịch Dương, nghĩa là tha thứ một số lỗi trong nhập liệu. Ví dụ, nếu cờ này được bật (nhận giá trị true) thi hệ thống sẽ tự động chuyển ngày tháng nhập vào không thật chính xác theo lịch, ví dụ February 30, 1999 thành March 2, 1999. Điều này có vẻ nguy hiểm, song hệ thống Java vẫn chuyển theo mặc định, nếu không đặt lại cờ lenient.

Ví dụ 8.2. Viết chương trình hiển thị ngày giờ cùa máy tính hiện thời theo các khu vực và theo dạng: DEFAULT, LONG, MEDIUM, SHORT được người sử dụng lựa chọn ở các ComboBox: Locale, Date style, Time style. Ví dụ, khi người sừ dụng chọn vùng Ba Lan (Polish) và dạng hiển thị ngày là FULL, dạng thời gian là LONG thì hệ thống sẽ hiển thị

trong đó PoniedzaLek là thứ Hai, Wrzesieh là tháng Chín.

// DateFormatTest.java

import javax.swing; import java.awt.*; import java.awt.event; import java.text.*; import java.util.*;

public class DateFormatTest{

public static void main(String args[]){

JFrame fr = new DateFormatFrame();        1

fr.show();

}

class DateFormatFrame extends JFrame{

private Locale!] locales; private Date currentDate; private Date currentTime;

private DateFormat currentDateFormat; private DateFormat currentTimeFormat;

private JComboBox combo = new JComboBoxO; private EnumCombo dateStyleCombo

= new EnumCombo(DateFormat.class,

new string[] {“Default”, “Full”, “long”, “Msdiirn”, “Short”}); private EnumCombo timeStyleCombo

= new EnumCombo(DateFormat.class,

new String[] {“Default”, “Rill”, “Lang”, “Ffediun”, “short”});

private JButton dateButton = new JButton(“Parse Date”); private JButton timeButton = new JButton(“Parse Time”); private JTextField dateText = new JTextField(30); private JTextField timeText = new JTextField(30); private JTextField parseText = new JTextField(30); private JtbeckBox lenientChedSox = new JCheckBox (“Parse lenient”, true);

public DateFormatFrame}){ setsize(400, 200); setTitle (“Date Format”); addWindowListener(new WindowAdapter(){

public void windowclosing(WindowEvent e){ System.exit(0) ;

}

}) ;

getContentPane().setLayout(new GridBagLayout());

GridBagConstraints gbc = new GridBagConstraints(); gbc.fill = GridBagConstraints.NONE; gbc.anchor = GridBagConstraints.EAST; add(new JLabel(“Locale”), gbc, 0, 0, 1, 1); add(new JLabel(“Date style”), gbc, 0, 1, 1, 1); add(new JLabelC’Time style”), gbc, 2, 1, 1, 1);

add(new JLabel{“Date”), gbc, 0, 2, 1, 1); add(new JLabel(“Time”), gbc, 0, 3, 1, 1);

gbc.anchor = GridBagConstraints.WEST; add(combo, gbc, 1, 0, 2, 1); add(dateStyleCombo, gbc,        1, 1,  1,  1);

add(timeStyleCombo, gbc,        3, 1,  1,  1);

add(dateButton, gbc, 3, 2, 1, 1); add(timeButton, gbc, 3, 3, 1, 1); add(lenientCheckBox, gbc, 0, 4, 1, 1); gbc.fill = GridBagConstraints.HORIZONTAL; add(dateText, gbc, 1, 2,   2,                                        1);

add(timeText, gbc, 1, 3,           2, 1);

locales = DateFormat.getAvailableLocales(); for(int i = 0; i < locales.length; i++)

combo.addltem(locales[i].getDisplayName()); ccmbo.setSelectedItsn(Locale.getDefaultO .getDisplayName ()); currentDate = new Date(); currentTime = new Date(); updateDisplay();

ActionListener listener = new ActionListener()(

public void actionPerfoimed(ActionEvent evt){ updateDisplay();

}

};

combo.addActionListener(listener); dateStyleCombo.addActionListener(listener); timeStyleCombo.addActionListener(listener);

dateButton.addActionListener new ActionListener(){

public void aetionPerformed(ActionEvent evt){

String d = dateText.getText(); try{

currentDateFormat.setLenient(

lenientCheckBox.isSelected()

);

Date date = currentDa’teFormat .parse (d); currentDate = date; updateDisplay();

}catch(ParseException e){

dateText.setText(“Parse error: ” + d);

}

catch(IllegalArgumentException e){ dateText.setText(“Argument error: ” + d);

}

}) ;

timeButton.addActionListener( new ActionListener()(

public void actionPterformed (ArtionEvent evt) { String t = timeText.getText(); try {

currentDateFormat.setLenient( lenientCheckBox.isSelected()); Date date = currentTimeFormat.parse(t); currentTime = date; updateDisplay();

}catch (ParseException e.) {

timeText.setText(“Parse error: ” + t);

}

catch(IllegalArgumentException e){ tirreText. setText (“Argument error: ” + t);

}

public void add(Component c, GridBagConstraints gbc, int x, int y, int w, int h){ gbc.gridx = x; gbc.gridy = y; gbc.gridheight = h; gbc.gridwidth = w; getContentPane().add(c, gbc);

)

public void updateDisplay(){

Locale currentLocale =

locales [ combo.getSelectedlndex()]; int dateStyle = dateStyleCombo.getValue(); currentDateFormat =

DateFormat.getDateInstance(dateStyle, currentLocale); String s = currentDateFormat.format(currentDate); dateText.setText(s) ;

int timeStyle = timeStyleCombo.getValue(); currentTimeFormat =

DateFormat.getTimelnstance(timeStyle, currentLocale); String t = currentTimeFormat.format(currentTime); timeText.setText(t);

}

)

class EnumCombo extends JComboBox {

public EnumCombo(Class cl, StringH labels) { for(int i – 0; i < labels.length; i++){

String label = labels[i];

String name = label. toUpperCase (). replace (‘                            ’_’);

int value = 0; try {

java.lang.reflect.Field f = cl.getField(name); value = f.getlnt(cl);

}catch(Exception e){

label = “(” + label +

}

table.put(label, new Integer(value)); addltem(label);

}

setSelectedltem (labels [0] ) ;

}

public int getValue(){

return ((Integer)table.get(getSelectedltem())).intValue();

}

private Map table = new HashMap();

}

Java.text.DateFomat

  • static Locale[] getAvailableLocales()

Nhận lại một danh sách các đối tượng khu vực mà E&teFormat hỗ trợ.

  • static DateFormat getDatelnstance(int dateStyle)
  • static DateFormat getDatelnstance(int dateStyle, Locale 1)
  • static DateFormat getTìmelnstance(int timeStyle)
  • static DateFormat getDateTimeInstance(int timeStyle, Locale 1)
  • static DateFormat  getDateTimelnstance(int dateStyle,  int tiraeStyle)
  • static DateFormat  getDateTimelnstance(int dateStyle,  int timeStyle, Locale 1)

Nhận lại khuôn dạng cho ngày, giờ, ngày và giờ theo khu vực cùa máy mặc định hoặc khu vực cho trước bởi 1

  • String format(String s)

Nhận lại xâu kết quả cùa ngày / giờ theo khuôn dạng qui định.

  • Date parse(String s)

Chuyển xâu s sang ngày / giờ theo khuôn dạng qui định.

  • void setLenient(boolean b)
  • boolean isLenientO

Đặt cờ và kiểm tra trạng thái của cờ lenient phục vụ cho việc chình sừa ngày theo lịch khi dữ liệu đầu vào không tương thích.

  • void setCalendar(Calendar cal)
  • Calendar getCalendar()

Đặt và đọc đối tuợng lịch biểu để tách ra các thông tin về ngày, tháng, năm, giờ, phút, giây. Lịch biểu mặc định là Gregorian còn được gọi là Lịch Dưcmg,

  • void setTimeZone(TimeZone f)
  • TímeZone getTimeZone()

Đặt và đọc đổi tượng múi giờ phục vụ cho việc định dạng cho đúng với khu vực hiện thời và đúng lịch biểu.

  • void setNumberFormat(NumberFormat f)
  • NumberFormat getNumberFormat()

Đặt và đọc đối tượng khuôn số liệu sừ dụng để định dạng ngày, tháng, năm, giờ, phút, giây.