不要使用那些不贊成的方法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