GWT:在客户端上使用DateTimeFormat,在服务器上使用SimpleDateFormat

bas*_*sin 18 gwt

我有一个函数必须在客户端和服务器上以相同的方式工作,它格式化日期.

if (GWT.isClient())
{
  // Use DateTimeFormat
} else {
  // Use SimpleDateFormat
}
Run Code Online (Sandbox Code Playgroud)

GWT抱怨:没有源代码可用于SimpleDateFormat类型.这个错误并不是致命的(至少在开发模式下),但是令人烦恼并且无法抑制它.在http://groups.google.com/group/google-web-toolkit/browse_thread/thread/981247fca161c287上找到了类似的问题.在那里他们建议:

您可以提供SimpleDateTimeFormat的虚拟超源实现,以便它可以编译.

我试过了.现在Eclipse抱怨:

java.text声明的包"java.text"与预期的包"foo.jre.java.text"SimpleDateFormat.java不匹配

Mic*_*cik 29

您可以com.google.gwt.i18n.shared.DateTimeFormat在服务器和客户端上使用:

调用受保护的构造函数以避免GWT.create

String pattern = "yyyyMMdd"; /*your pattern here*/ 
DefaultDateTimeFormatInfo info = new DefaultDateTimeFormatInfo();
DateTimeFormat dtf = new DateTimeFormat(pattern, info) {};  // <= trick here
Run Code Online (Sandbox Code Playgroud)

Date d = dtf.parse("20120301");
CalendarUtil.addDaysToDate(d, -1);
String s = dtf.format(d);
// s now contains "20120229"
Run Code Online (Sandbox Code Playgroud)

诀窍是通过扩展实现DateTimeFormat用,所以我们可以使用受保护的构造DateTimeFormatInfo,我们使用new DefaultDateTimeFormatInfo(),以避免调用GWT.create


Tho*_*yer 0

您必须告诉 Eclipse 不要编译您的超级源 Java 文件。如果您使用 Maven,只需将其移动到 src/main/resources 即可;否则,从 Eclipse 的构建路径中排除“jre”包。

...话虽这么说,我宁愿对使用 SimpleDateFormat/DateTimeFormat 的类进行超级源,和/或将其移至您要超级源的帮助器类。