GWT (Google Web Toolkit) 將 Java 代碼編譯為 JavaScript 運行在瀏覽器端。客戶端代碼不能使用 java.text.SimpleDateFormat 等 JRE 類庫,必須使用 GWT 提供的 com.google.gwt.i18n.client.DateTimeFormat 進行日期格式化與解析。
import com.google.gwt.i18n.client.DateTimeFormat;
// 獲取格式化器 (線程安全、不可變)
DateTimeFormat sdf = DateTimeFormat.getFormat("yyyy-MM-dd");
DateTimeFormat sdf2 = DateTimeFormat.getFormat("yyyy-MM");
DateTimeFormat sdf3 = DateTimeFormat.getFormat("yyyy-MM-dd HH:mm:ss");
// 格式化 Date → String
Date date = new Date();
String formatted = sdf.format(date); // "2024-01-15"
// 解析 String → Date
Date parsed = sdf.parse("2024-01-15");
public class StatsExchangeCoinView extends BaseContentPanel implements StatsExchangeCoinPresenter.Display {
private DateRangeField dateRangeField; // 自定義日期範圍組件
private void initToolBar() {
// ... 其他工具欄組件
dateRangeField = WidgetCreateUtil.createDateRangeField("start", "end", "選擇日期");
// 設置默認值:本月 1 日 至 今日
Date date = new Date();
DateTimeFormat sdf = DateTimeFormat.getFormat("yyyy-MM-dd");
DateTimeFormat sdfMonth = DateTimeFormat.getFormat("yyyy-MM");
String startStr = sdfMonth.format(date) + "-01"; // 如 "2024-01-01"
String endStr = sdf.format(date); // 如 "2024-01-15"
dateRangeField.setValue(new String[]{startStr, endStr});
getToolBar().add(dateRangeField);
// ...
}
// 參數提交時獲取日期範圍
protected void parameters(LoadConfig config) {
if (dateRangeField.getValue() != null
&& !dateRangeField.getStartTimeString().isEmpty()
&& !dateRangeField.getEndTimeString().isEmpty()) {
config.set("startDate", dateRangeField.getStartTimeString());
config.set("endDate", dateRangeField.getEndTimeString());
}
}
}
| 字母 | 含義 | 示例 |
|---|---|---|
| y | 年 | yyyy=2024, yy=24 |
| M | 月 | MM=01, M=1 |
| d | 日 | dd=01, d=1 |
| H | 時 (0-23) | HH=13, H=13 |
| m | 分 | mm=05, m=5 |
| s | 秒 | ss=09, s=9 |
| S | 毫秒 | SSS=123 |
| E | 星期 | EEE=Mon, EEEEE=Monday |
| z | 時區 | z=GMT+08:00 |
EntryPoint、UI 組件、RPC 回調) 需用 DateTimeFormat;服務端代碼繼續用 SimpleDateFormat。DateTimeFormat 實例不可變,可安全作為静態常量複用。getFormat 會緩存實例,重複調用無額外開銷。java.time 部分 API (通過 gwt-jre-emul),但 DateTimeFormat 仍為首選。
// 完整 View 類代碼見原文,包含 Grid、PagingToolBar、ColumnConfig 等 GXT 組件用法