How to Add Date / Time from OData Service Correctly to UI?

There is no need for “hacky approaches” or custom formatters in case you simply want to display the time (or date) in a human readable form. UI5 comes with the concept data typesdoc which has the following advantages:

  • Let UI5 format,
    parse, and even validate the value for you.
  • Supports two-way data binding in contrast to formatter.
  • Additional format options or input constraints can be defined.

In our case, the appropriate type for displaying the value of Edm.Time is sap.ui.model.odata.type.Time.api

Sample

From https://embed.plnkr.co/F3t6gI8TPUZwCOnA:

<Table items="{carrierFlights}"
  xmlns="sap.m"
  xmlns:core="sap.ui.core"
  core:require="{
    DateTimeType: 'sap/ui/model/odata/type/DateTime',
    TimeType: 'sap/ui/model/odata/type/Time'
  }"><!-- ... -->
  <ColumnListItem>
    <!-- Date only -->
    <Text text="{
      path: 'fldate',
      type: 'DateTimeType',
      constraints: {
        displayFormat: 'Date'
      }
    }" />
    <!-- Time only -->
    <Text text="{
      path: 'departureTime',
      type: 'TimeType',
      formatOptions: { style: 'long' }
    }" />
    <!-- works with any other controls such as DatePicker, TimePicker, etc.. -->
  </ColumnListItem>
</Table>

Note: About the core:require-syntax, see Require Modules in XML View and Fragment which is supported as of UI5 1.69. For lower versions, use the following syntax:

type: 'sap.ui.model.odata.type.(Date)Time'

Result

UI5 example

For more information, including how to bind DateTime or DateTimeOffset in DateRangeSelection, take a look at the documentation topic Date and Time Related Controls: Data Binding.


TL;DR

  1. Check which type the entity property is using in the service $metadata document.

  2. Use one of the OData types in the property binding:

    xmlns:core="sap.ui.core"
    core:require="{ RequiredODataType: 'sap/ui/model/odata/type/<appropriateType>' }"
    value="{
      path: 'myODataModel>myProperty',
      type: 'RequiredODataType',
      <Add formatOptions & constraints here depending on the required OData type>
    }"

    For a complete list of available OData types, see API Reference: sap.ui.model.odata.type.

Leave a Comment