SAPUI5 Development

Formatting Date and Time in SAPUI5 using DateFormat class

            Displaying dates and times is very important in applications.From Backend Date and Time comes as Date objects(for eg:date in json: /Date(1354664600000)/ date in xml will be in another format).Today we will see how to format Date and Time in SAPUI5 using sap.ui.core.format.DateFormat class.DateFormat is a static class for formatting and parsing date and time values according to a set of format options.
             We can make use of five different types of date formats.They are short,medium,long,full and relative.relative dates are displayed as texts like today,5 days etc.We will make use of binding for the formatting of date and time.

Pre-requisites

1. SAPUI5 framework.


Steps

  1. Create an sapui5 application and add northwind odataservice to the application and bind Orders entityset to the sap.m.List control in the application.If you don't know how please visit previous tutorials.
  2. Time to code.Add below code in view.

  3. 
    <List items="{/Orders}">
     <items>
      <ObjectListItem id="masterListItem"
                                title="{path: 'OrderDate', type: 'sap.ui.model.type.DateTime',formatOptions: { style: 'medium', strictParsing: true, relative: true }}"
           intro="{CustomerID}">
      </ObjectListItem>
     </items>
    </List>
    

  4. Run the application and you can see the dates are formatted.Try all options yourself and see the difference.
I am sharing sample code for you.In this I have used json model  instead of OData model to see the difference in relative type of formatting.
DateTime in XML view
DateTime in JS view
Make sure you have given property data-sap-ui-compatVersion="edge" while bootstrapping sapui5 in index.html.
Note:I have used additional property in formatOptions in sample because the date is in string format.From backend it is coming as date object.So inorder to tell the date type how to parse the date string i have given source: { pattern: 'yyyy-MM-ddTHH:mm:ss'}
If you enjoyed this post, Please Share!!

0 comments :

Post a Comment

Powered by Blogger.