TimeZone and DateFormatter

Hi

I have a table with some columns with date information, now, even though both properties have the same date and time, the one with DateFormatter is not having in mind the user time zone (Its showing a difference of three hours). Is there any work around so date formatter does not ignore user time zone?

 <column id="statSnapshotEvent.eventDateTime"/>        
 <column id="logDateTime">
                    <formatter class="com.haulmont.cuba.gui.components.formatters.DateFormatter"
                               format="dd/MM/yyyy HH:mm:ss.SSS"/>
 </column>

Hi Ronald,

DateFormatter doesn’t support user timezone. It shows datetime in the server timezone.
You can create formatter that accept the user time zone and define formatter for the table column:

public class DateFormatter implements Formatter<Date> {

    private Element element;

    protected UserSessionSource userSessionSource = AppBeans.get(UserSessionSource.NAME);
    protected Messages messages = AppBeans.get(Messages.NAME);

    public DateFormatter(Element element) {
        this.element = element;
    }

    @Override
    public String format(Date value) {
        if (value == null) {
            return null;
        }
        String format = element.attributeValue("format");
        if (StringUtils.isBlank(format)) {
            String type = element.attributeValue("type");
            if (type != null) {
                FormatStrings formatStrings = Datatypes.getFormatStrings(userSessionSource.getLocale());
                if (formatStrings == null)
                    throw new IllegalStateException("FormatStrings are not defined for " + userSessionSource.getLocale());
                switch (type) {
                    case "DATE":
                        format = formatStrings.getDateFormat();
                        break;
                    case "DATETIME":
                        format = formatStrings.getDateTimeFormat();
                        break;
                    default:
                        throw new RuntimeException("Illegal formatter type value");
                }
            }
        }

        if (StringUtils.isBlank(format)) {
            return value.toString();
        } else {
            if (format.startsWith("msg://")) {
                format = messages.getMainMessage(format.substring(6, format.length()));
            }
            DateFormat df = new SimpleDateFormat(format);
            UserSession userSession = userSessionSource.getUserSession();
            if (userSession.getTimeZone() != null) {
                df.setTimeZone(userSession.getTimeZone());
            }
            return df.format(value);
        }
    }

We plan to implement user timezone in the default formatter. See issue: https://youtrack.cuba-platform.com/issue/PL-10254

Thanks,
Andrey

1 Like