Search code examples
javascriptjavagwt

How to get GWT dates to be formatted correctly?


How do you get today's date in MM/dd/yyyy format? I've followed the docs and examples. This is supposed to do it:

Date today = new Date();
DateTimeFormat fm = DateTimeFormat.getFormat("MM/dd/yyyy");
String date = fm.format(today);
return new Object[][] {
        new Object[] { "This is a note", date},
        new Object[] { "This is a very very very long note", date}
};

But instead it puts the following in the date cell of the grid:

Sun Mar 07 2021 00:00:00 GMT-0700 (Mountain Standard Time)

So then I tried to do it javascript like this:

public native String getTodaysDate() /*-{
    return new Date().toLocaleDateString();
    }-*/;

private Object[][] getNoteData() {
    String date = getTodaysDate();

Which produces the same result.

Such a simple task sucks up so much time! Suggestions?

EDIT: I'm adding more code for people to better diagnose the problem.

private Panel createNotesTable() {
    Panel panel = new Panel();

    RecordDef recordDef = new RecordDef(
            new FieldDef[] { 
                    new StringFieldDef("note"), 
                    new DateFieldDef("date"), 
            }
    );

    GridPanel grid = new GridPanel();
    Object[][] data = getNoteData();
    MemoryProxy proxy = new MemoryProxy(data);

    ArrayReader reader = new ArrayReader(recordDef);
    Store store = new Store(proxy, reader);
    store.load();
    grid.setStore(store);

    ColumnConfig[] columns = new ColumnConfig[] {
            new ColumnConfig("Note", "note", 130, true, null, "note"),
            new ColumnConfig("Date", "date", 65, true)
    };
    ColumnModel columnModel = new ColumnModel(columns);
    grid.setColumnModel(columnModel);

    grid.setStripeRows(true);

    panel.add(grid);
    return panel;
}

private Object[][] getNoteData() {
    Date today = new Date();
    DateTimeFormat fm = DateTimeFormat.getFormat("MM/dd/yyyy");
    String date = fm.format(today);
    GWT.log("date=" +date);  //date is formatted correctly
    //but when it is put into the cell, it gets reformatted back to a long version
     return new Object[][] {
            new Object[] { "This is a note", date},
            new Object[] { "This is a very very very long note", date}
    };
}

Solution

  • The reason was because I was using a

    new DateFieldDef("date")
    

    instead of

    new StringFieldDef("date"),
    

    Thanks to commenters for the tip!