I have got a SAPUI5 table that is populated from an OData Model. One of its columns is a date/time field that I'd like to format, but I can't figure out how to do it in SUI5.
This is what I'm doing now:
var tableModel = new sap.ui.model.odata.ODataModel("...");
var table = new sap.ui.table.DataTable();
table.setModel(tableModel);
table.addColumn(new sap.ui.table.Column({
label: new sap.ui.commons.Label({text: "Date"}),
template: new sap.ui.commons.TextView().bindProperty("text", "DATE"),
sortProperty: "DATE",
filterProperty: "DATE"
}));
Here's the first couple of lines of output (my browser language is German):
All I want to do is change the date and time format to, say, mm/dd/yyyy hh:mm
I did some searching, and the following question is exactly my problem - but there is an accepted answer that either I do not understand or that does not actually solve the problem:
Date format in a table SAPUI5
I realize this might be a trivial question and I just missed how to do this easily, or it is dealt with in one of the official tutorials. In that case, please just point me to it in the comments and I will delete this question.
Using a formatter function is very flexible, but if you're looking for something simpler without having to write your own format logic, you can consider using the type property rather than the formatter like this:
template: new sap.ui.commons.TextView().bindProperty("text", {
path: "OrderDate",
type: new sap.ui.model.type.Date({pattern: "MM/dd/yyyy hh:mm"})
})
May also be worth considering the standard model formatters: sap.ui.model.type.DateTime and sap.ui.model.type.Date
template: new sap.ui.commons.TextView().bindProperty("text", {
path: "DATE",
type: new sap.ui.model.type.DateTime,
formatOptions: { style: "medium" }
})
XML example (as always use XML ;)
<Text text="{path : 'runDateTime',
type : 'sap.ui.model.type.DateTime',
formatOptions: { style : 'medium'}}" />
Since using UI5 is often a conversation about applying a standard view for an application, using the standard formatting may be a useful idea.
use formatter-function:
var tableModel = new sap.ui.model.odata.ODataModel("...");
var table = new sap.ui.table.DataTable();
table.setModel(tableModel);
table.addColumn(new sap.ui.table.Column({
label: new sap.ui.commons.Label({text: "Date"}),
template: new sap.ui.commons.TextView({
text : {
path : 'DATE',
formatter : function(value){
return /* TODO: some format logic */;
}
}
}),
sortProperty: "DATE",
filterProperty: "DATE"
}));
I am also adding how to format numbers using the formatter function.
<template> = new sap.ui.commons.TextField().bindProperty("<value>",{
path: "<GROSSVALUE>",
type: new sap.ui.model.type.Integer({
maxIntegerDigits: 10,
minFractionDigits: 2,
maxFractionDigits: 2,
groupingEnabled: true,
groupingSeparator: ",",
decimalSeparator: "."
})});
Related
I have couple of weird problems with the sap.m.DatePicker. As I always do, I searched for topics via google, they helped me, but not entirely.
What I want to achieve
I would like to have a sap.ui.table.Column in a sap.ui.table.Table and this column should have a template: new sap.m.DatePicker() with date formatted as dd.MM.yyyy.
What I have done so far
I am using a v2.ODataModel to populate a sap.ui.table.Table from an OData service. Everything went well until I decided to have the dates in the corresponding column displayed in a preferred format. At first, I was using only these properties, related to formatting in the DatePicker's constructor:
new DatePicker({
displayFormat: "dd.MM.yyyy",
valueFormat: "yyyy-MM-dd",
value: "{" + fieldName + "}",
//...,
})
In this way, all dates are displayed in the following format
Sun Aug 06 2017 03:00:00 GMT+0300 (FLE Daylight Time)
I remember yesterday reading in a documentation, that when I have binding, displayFormat will be ignored, which to me is ... I don't understand why is that.
Anyway, I found a solution, which gives the advice to set value like this:
value: {
path: colName,
type: new sap.ui.model.type.Date({
pattern: "dd.MM.yyyy",
//source: { pattern: "yyyy-MM-dd HH:mm:ss:fff" }
})
}
At first, it seems to work well and the date is formatted and displayed correctly, but when I try to modify the date in a row... For example, I choose August 6th 2017. What is saved to the database via the OData service is 2017-06-08 00:00:00.000. This is not August 6th but June 8th. I select August 2nd - in the database, I see 2017-02-08 00:00:00.000 - February 8th. Seems like the month and day get switched. If I select, for example, August 30th, the change is not saved. As far as I understand what the problem is - there is no month with number 30, so it refuses to save it. Totally makes sense. :D
Then I tried to add/uncomment the line source: {}. Now for every row, the date column shows empty, as if every row in the database has null as value in that date column.
Next, I tried to remove displayFormat: "dd.MM.yyyy", valueFormat: "yyyy-MM-dd" from the definition of the DatePicker template - nothing changed. Interesting is - no matter if I remove those two lines or not, I can still change the date of a row (the change gets saved to the database), although month and day are still switched.
Then I came across another solution, which said, that I should add a formatter like this:
value: {
path: colName,
formatter: function(val) {
return sap.ui.core.format.DateFormat.getDateInstance({
pattern: "dd-MM-yyyy"
}).format(val);
}
}
This way, it all seems to work as it should. Now you may ask did I give up using the format dd.MM.yyyy. Answer is "No!", it just doesn't work.
So, this is the main question, that I want to ask: What's wrong with this formatting? No matter what other symbol I use, comma, dash, it always works (dd-MM-yyyy or dd,MM,yyyy). The dates are displayed with the corresponding symbol. When I try to use dd.MM.yyyy, it errors like that:
and like that:
Thank you all for your help! Will appreciate it!
Edit: I have just come up with the idea to workaround this issue. Unfortunately, it doesn't work and produces the exact same error, described above with pictures. Here is the nonworking solution:
return sap.ui.core.format.DateFormat.getDateInstance({
pattern: "dd-MM-yyyy"
}).format(val).replace(/\-/g, '.');
Try using "dateValue" + "displayFormat" properties like here:
https://plnkr.co/edit/wkHv9s?p=preview
<DatePicker
dateValue="{testModel>/myDate}"
displayFormat="dd.MM.yyyy" />
sap.m.DatePicker with date formatted as dd.MM.yyyy
I am using a v2.ODataModel.
In that case, bind value with the following options:
<DatePicker value="{
path: 'ReleaseDate',
type: 'sap.ui.model.odata.type.DateTime',
formatOptions: {
pattern: 'dd.MM.yyyy'
},
constraints: {
displayFormat: 'Date'
}
}"/>
(Assuming "ReleaseDate" is of type Edm.DateTime)
Here is a demo you can run:
sap.ui.getCore().attachInit(() => sap.ui.require([
"sap/ui/model/odata/v2/ODataModel",
"sap/ui/core/mvc/XMLView",
], function(ODataModel, XMLView) {
"use strict";
const model = new ODataModel({
serviceUrl: [
"https://cors-anywhere.herokuapp.com/", // proxy
"https://services.odata.org/V2/(S(SO45750998))/OData/OData.svc/",
].join(""),
tokenHandling: false,
defaultBindingMode: "TwoWay",
});
const viewDefinition = `<mvc:View xmlns:mvc="sap.ui.core.mvc" height="100%">
<DatePicker id="dp" xmlns="sap.m" width="8.25rem" placeholder="Date"
binding="{
path: '/Products(0)',
parameters: {
select: 'ID, ReleaseDate'
}
}"
value="{
path: 'ReleaseDate',
type: 'sap.ui.model.odata.type.DateTime',
formatOptions: {
pattern: 'dd.MM.yyyy'
},
constraints: {
displayFormat: 'Date',
nullable: false
}
}"
/>
</mvc:View>`;
const createView = () => XMLView.create({
definition: viewDefinition,
models: model,
afterInit: function() {
const fn = e => e.getSource().getBindingContext().getModel().submitChanges();
this.byId("dp").attachChange(fn);
},
}).then(view => sap.ui.getCore().getMessageManager().registerObject(view.placeAt("content"), true));
Promise.all([
sap.ui.getCore().loadLibrary("sap.m", true),
sap.ui.getCore().loadLibrary("sap.ui.unified", true),
]).then(createView);
}));
<script id="sap-ui-bootstrap" src="https://ui5.sap.com/resources/sap-ui-core.js"
data-sap-ui-libs="sap.ui.core"
data-sap-ui-theme="sap_fiori_3"
data-sap-ui-async="true"
data-sap-ui-compatversion="edge"
data-sap-ui-xx-waitForTheme="init"
></script>
<body id="content" class="sapUiBody sapUiSizeCompact"></body>
As you can see in the network panel, the selected date is sent properly to the OData service without any issues. Just make sure to use the type sap.ui.model.odata.type.DateTime for fields that are of type Edm.DateTime.
For more information, see:
Documentation topic: Date and Time Related Controls: Data Binding
Related question: How to Add Date / Time from OData Service Correctly to UI?
I get array of date from json as 1420185600000,1420531200000,1420617600000,1420704000000,1420790400000,1420876800000. How do I format it to show the correct date in the XAxis labels of the highcharts?
You need to tell highcharts that the xAxis is a date type.
xAxis: {
type: 'datetime'
},
You may need extra formatting if you want the date displayed in some form other than the default. That can be done via the labels.formatter.
Sample code that lets you do what you want (minus what formatting you want your date in):
xAxis: {
categories: [1420185600000,1420531200000,1420617600000,1420704000000,1420790400000,1420876800000],
labels: {
formatter: function () {
return new Date(this.value);
}
}
},
You would then need to determine what parts of your new date string you actually want to show. The sample above doing return Date(this.value) is the kitchen sink approach.
UPDATE: If you want the strings formatted, Highcharts gives you functions to set up the date string. See this fiddle (same as fiddle linked in the comments below with formatter using highcharts): http://jsfiddle.net/CaptainBli/psd3ngsh/13/
xAxis: {
type: "datetime",
categories: xArray,
labels: {
formatter: function () {
return Highcharts.time.dateFormat('%Y-%m-%d %H:%M:%S.%L', new Date(this.value));
}
}
},
arrayOfDatesFromJson = arrayOfDatesFromJson.map(function (element) {
return new Date(element);
});
simple question but I can't figure out how to resolve it.
I'm receiving a date with hour from JSON with this format :
"date_deb":"2013\/12\/28 23:00:00"
Note that the \ are for escaping the / and are not displayed.
I would like to display this dates in this format into my grid :
"28/12/2013 23:00:00"
I've tried this into my fields definition:
{name:'date_deb', type: 'date', dateFormat: 'd-m-Y H:i:s'}
But it's not working, nothing is displayed.
By checking the ExtJS docs, I've seen this :
dateReadFormat
I'm using ExtJS4.2
In your field definition provide the dateFormat as it is returned from the server:
{name:'date_deb', type: 'date', dateFormat: 'Y/m/d H:i:s'}
and then in your column config use ExtJS's built-in dateRenderer with the format you'd like to render your dates with:
renderer: Ext.util.Format.dateRenderer('d/m/Y H:i:s')
You'll only need dateReadFormat and dateWriteFormat if you have a reader (to read data from server) AND a writer (to send modified data back to server) which need different date formats. Otherwise dateFormat will apply as the default format for both.
If the above doesn't work for you, try adding xtype: 'datecolumn' in your grid's 'columns' config.
columns: [{
text : 'date',
dataIndex: 'LoginDateTime',
xtype: 'datecolumn',
format: 'Y-m-d g:i A',
}]
This should work.
use this function to render date for grid
In your column definition define renderer as this
renderer: renderDate
example { dataIndex: 'TaskEndDate', header: 'PlannedEndDate', flex: 1, renderer: renderDate },
function renderDate(value)
{
if (value == '' || value == undefined) {
return '';
}
else {
getDate = new Date(parseInt(value.substr(6)));
}
return Ext.util.Format.date(getDate, 'm-d-Y');
}
In your column config use "formatter".
formatter: 'date("d/m/Y H:i:s")'
Well there seems to be a multitude of similar questions, but none that I can find answering this specific question.. so here goes..
Have a working Kendo UI grid. My datasource is returning a timestamp - here's the JSON response coming back to the code:
You'll notice that the next line is also a date.. returned by MySQL as a standard DateTime format - which I would be happy to use directly. But I've converted the date to a timestamp which I thought would be more universal. (??)
Now I need to do two things - format the timestamp into a readable date and edit the date so it can be saved back to the datasource. But let's tackle formatting first.
My code to display the column currently looks like this:
{ title: "Trial<br>Date",
field: "customer_master_converted_to_customer_date",
format: "{0:d/M/yyyy}",
attributes: {
style: "text-align: center; font-size: 14px;"
},
filterable: true,
headerAttributes: {
style: "font-weight: bold; font-size: 14px;"
}
},
Although I've tried..
toString(customer_master_converted_to_customer_date, "MM/dd/yyyy")
.. and several variations of that - in terms of format string. And yes, I've tried entering:
type: "date",
No matter what I do, I only get the timestamp.
Anyone?
You need to convert the timestamp to a JavaScript date first. Here is a sample implementation:
$("#grid").kendoGrid({
dataSource: {
data: [
{ date: 1371848019 }
],
schema: {
model: {
fields: {
date: {
type: "date",
parse: function(value) {
return new Date(value * 1000);
}
}
}
}
}
}
});
Here is it live: http://jsbin.com/utonil/1/edit
I just had the same problem and i tried this and now works perfectly, good luck.
template :#= kendo.toString(new Date(parseInt(dateOfBirth)), 'yyyy-MM-dd')#"
whre dateOfBirth is the date to format, the result will be like this : 2015-09-11.
good luck.
Thank you #Atanas Korchev, that worked for me, here is what I ended up doing:
// in datasource
schema:{
model: {
fields: {
date: { type: "date",
parse: function(value) {
return new Date(value);
}
}, // … other fields
// in columns
columns: [
{
field: "date",
title: "Date",
type: "date",
format: "{0:dd MMM yyyy}"
},
// ... other columns
]
The easiest way to use the TimeStamp format data from your database for KendoGrid.
https://stackoverflow.com/a/67106362/5671943
<kendo-grid-column class="CreatedAt" field="CreatedAt" title="title"
[width]="120" [headerStyle]="{'background-color': '#36455a','color': '#fff'}"
[style]="{'background-color': '#36455a','color': '#fff'}">
<ng-template kendoGridCellTemplate let-dataItem>
{{dataItem.CreatedAt | date:"yyyy/MM/dd HH:mm:ss"}}
</ng-template>
</kendo-grid-column>
I have the following date field i want to get date of one day before , how can i get that ?
In my form panel
items: [{
fieldLabel: 'Start Date',
name: 'fromdate',
ref: '../fromdate',
id: 'fromdate',
vtype: 'daterange',
value: new Date(),
endDateField: 'todate' // id of the end date field
}, {
fieldLabel: 'End Date',
name: 'todate',
id: 'todate',
vtype: 'daterange',
value: new Date(),
startDateField: 'fromdate' // id of the start date field
}]
Today I am getting 03/23/2011 but I want 03/22/2011 How I can get 03/22/2011?
Speaking ExtJS language, you can use Ext.Date library for manipulation dates. For example:
Ext.Date.add (new Date(),Ext.Date.DAY,1)
Depending on your code logic, you can modify the default value of date field by several ways:
1) In the item's value configuration:
{
...
vtype: 'daterange',
value : Ext.Date.add (new Date(),Ext.Date.DAY,1),
fromDateField: 'fromdate',
...
}
2) During the component's event. Basically, ExtJS containers have initComponent method which is the most first running, but be sure to set your code after callParent() method in order to access items collection. Example:
initComponent: function() {
...
this.callParent(arguments);
this.items.getByKey('fromdate').value = Ext.Date.add (new Date(),Ext.Date.DAY,1);
...
}
Try this:
new Date().add(Date.DAY, -1);
Or this:
var date = new Date();
date.setDate(date.getDate()-1);