不要使用那些不赞成的方法GWT中的Date类。
如果您不想使用GWT的第三方Date实现,那么您暂时使用DateTimeFormat
以及字符串操作的组合作为解决方法,直到GWT为处理日期提供一些更好的支持。
For date -
DateTimeFormat.getFormat("d-M-yyyy").format(new Date()).split("-")[0]
For month -
DateTimeFormat.getFormat("d-M-yyyy").format(new Date()).split("-")[1]
For year -
DateTimeFormat.getFormat("d-M-yyyy").format(new Date()).split("-")[2]
编辑 - 类似地,应避免使用新的日期取决于浏览器和日期范围(YY,毫米,DD)已经到来的不一致。
我用一个简单的DateUtil类来创建和分析在GWT Date对象,也许一些对你有用 -
(警告:非常简陋,和正在进行的工作)
public class DateUtil
{
private static final String D_M_YYYY = "d-M-yyyy";
private static final String DATE_SEPARATOR = "-";
public static Date getDate(Integer dd, Integer mm, Integer yyyy)
{
if (dd == null || mm == null || yyyy == null)
return null;
Date retVal = null;
try
{
retVal = DateTimeFormat.getFormat(D_M_YYYY).parse(dd + DATE_SEPARATOR + mm + DATE_SEPARATOR + yyyy);
}
catch (Exception e)
{
retVal = null;
}
return retVal;
}
public static String getDayAsString(Date date)
{
return (date == null) ? null : DateTimeFormat.getFormat(D_M_YYYY).format(date).split(DATE_SEPARATOR)[0];
}
public static String getMonthAsString(Date date)
{
return (date == null) ? null : DateTimeFormat.getFormat(D_M_YYYY).format(date).split(DATE_SEPARATOR)[1];
}
public static String getYearAsString(Date date)
{
return (date == null) ? null : DateTimeFormat.getFormat(D_M_YYYY).format(date).split(DATE_SEPARATOR)[2];
}
public static boolean isValidDate(Integer dd, Integer mm, Integer yyyy)
{
boolean isvalidDate = true;
try
{
String transformedInput = DateTimeFormat.getFormat(D_M_YYYY).format(getDate(dd, mm, yyyy));
String originalInput = dd + DATE_SEPARATOR + mm + DATE_SEPARATOR + yyyy;
isvalidDate = transformedInput.equals(originalInput);
}
catch (Exception e)
{
isvalidDate = false;
}
return isvalidDate;
}
}
什么样的第三方日期实现你会推荐? – Jla 2010-07-08 08:59:15
我没有在我的应用程序中使用复杂的日期算术,因此没有认真查找任何用于GWT的DateTime库。我知道有一个GwtDateTime实用程序(http://code.google.com/p/gwt-examples/wiki/gwtDateTime),但没有经过测试,不能担保。 YMMV – 2010-07-08 09:10:11
这些不能在单元测试:(:(除非你延长GWTTestCase这是缓慢的) – 2011-10-12 14:31:15