ExtJS: Date field writes the date one day back? - date

I'm using a 'Ext.form.field.Date' and on CRUD process it writes given date as one day back. I mean if I select 05 June 2018, it writes as 04 June 2018.
I've checked related model and widget itself but nothing seems weird! Why this could be?
Here is model statement and field;
Ext.define('MyApp.FooModel', {
extend: 'Ext.data.Model',
fields: [
{name: 'mydatefld', type: 'date', dateReadFormat: 'c', dateWriteFormat: 'Y-m-d'},
//and implementation
Ext.define('MyApp.BaseDateFld', {
extend: 'Ext.form.field.Date',
xtype: 'basedatefld',
format: 'd.m.Y',
flex: 1,
labelAlign: 'right',
name: 'MyDate Fld',
fieldLabel: 'MyDate Fld',
bind: '{currRec.mydatefld}'
});
Each time saves date as on XHR request payload;
2018-06-05T21:00:00.000Z //But should be 2018-06-06T06:05:00.000Z
Update:
I've tried change dateWriteForm to 'Y-m-d H:i:s' and 'Y-m-d H:i' but still noting changes on payload and keep decrease one day and sets time to 21:00:00
As well tried to change compouter TS to some another as #Alexander adviced but nothing changed.
Update 2:
I've over come the current issue but really a very DRY solution, so not safe!
Below there is insertion method (update method is almost same as this) and formating the related date value on here, thusly became success.
Server accepting the date format for this field as Y-m-d, so I've stated dateWriteFormat on model and submitFormat on datefield as 'Y-m-d' but it keeps write the date value with timestamp.
When I check rec param on method it is as 2018-06-06T21:00:00.000Z(The TZ part shouldn't be here!). And store param changes the givin date one day off as 2018-06-05T21:00:00.000Z.
Still not sure why I can't convert/format through model or field.
Thanks for advices.
recInsertion: function (rec, store) {
store.getProxy().url = store.getProxy().api.create;
rec.data.givindate = Ext.Date.format(rec.data.mydate, 'Y-m-d'); //This is current solution to format date! Which is really not safe and will cause DRY.
Ext.Ajax.request({
url: store.proxy.url,
method: 'POST',
jsonData: JSON.stringify(rec.data),
callback: function (options, success, response) {
Ext.GlobalEvents.fireEvent('showspinner');
if (success) {
Ext.GlobalEvents.fireEvent('refreshList');
}
else
Ext.GlobalEvents.fireEvent('savefailed');
}
});
},

Related

How to get selected date from ionic-2 calendar onchange() method

I am using ion2-calendar.
this is my html:
<ion-calendar [(ngModel)]="date"
(onChange)="onChange($event)"
[type]="type"
[format]="'YYYY-MM-DD'">
</ion-calendar>
and this is onchange in ts:
onChange($event) {
console.log("onchange event called");
console.log(moment().format('DD-MM-YYYY'));
}
This is my console:
onSelect event called
25-06-2018
But i am always getting current month and year,no matter which date I choose. Only the date value is changing.
Its showing current month and year in the console for all dates.
Can someone tell me how to get selected date in dd-mm-yy format from $event object.
Edit- This is what i get for console.log($event)
Moment {_isAMomentObject: true, _i: 1530297000000, _isUTC: false, _pf: {…}, _locale: Locale, …}
_d
:
Sat Jun 30 2018 00:00:00 GMT+0530 (India Standard Time) {}
_i
:
1530297000000
_isAMomentObject
:
true
_isUTC
:
false
_isValid
:
true
_locale
:
Locale {_calendar: {…}, _longDateFormat: {…}, _invalidDate: "Invalid date", ordinal: ƒ, _dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/, …}
_pf
:
{empty: false, unusedTokens: Array(0), unusedInput: Array(0), overflow: -2, charsLeftOver: 0, …}
__proto__
:
Object
It shows correct date of click.
It would be great if someone could tell me how to extract date from this .
$event of OnChange() is a moment object.
you can format like this: $event.format('DD-MM-YYYY')
moment() statement always generates current time like new Date().
you should use a statement like moment("1995-12-25") or other various statements.
For details, please have a look at this moment.js docs
update
To say the conclusion first,
.html (nothing changed)
<ion-content padding>
<ion-calendar [(ngModel)]="date"
(onChange)="onChange($event)"
[type]="type"
[format]="'YYYY-MM-DD'">
</ion-calendar>
.ts
onChange(event) {
console.log(event.format('DD-MM-YYYY')); // For actual usage.
console.log(moment(event).format('DD-MM-YYYY')); // the statement you might think about
}
the above code gives you what you want.
What I want to say is that you should not use moment() but moment(event). Because moment() returns moment instance which has current time while moment(event) returns moment instance which has the time event carries.
It seems like the Release Candidate version changed the output event to change instead of onChange and select instead of onSelect. Try using this:
<ion-calendar [(ngModel)]="date"
(change)="onChange($event)"
[format]="'YYYY-MM-DD'">
`
<ion-calendar [(ngModel)]="date" (change)="onChange($event)" [type]="type"
[format]="'YYYY-MM-DD'">
</ion-calendar>
date;
type: "string";
onChange(event) {
console.log(moment(this.date._d).format("YYYY-MM-DD"));
}

Aurelia converted values and dataTables

I'm using DataTables jQuery plugin in Aurelia component. using column ordering and it works well excluding columns with dates.
Inside this columns I'm using value-convertet to convert isoString value to DD.MM.YYYY date format. Value covreters usage leads to wrong date column ordering, but if I'm not using value-converter everything works well. Unfortunately I didn't find any reason why it doesn't work correctly.
Wrong filtering example: I see rows with date value like 27.05.2010 before 18.05.2017
DataTables init:
$('#searchResultsTable').dataTable({
destroy: true,
searching: false,
paging: false,
orderMulti: false,
order: [[ 2, "desc" ]],
dateFormat: 'DD.MM.YYYY'
});
Date value converter (using moment library):
import * as moment from 'moment';
export class DateFormatValueConverter {
toView(value: Date, format: string): string {
if (value) {
return moment(value).format(format);
}
return null;
}
fromView(value: string, format: string): Date {
var isValid = moment(value, format, true).isValid();
if (value && isValid) {
return moment(value, format).toDate();
}
return null;
}
}
UPDATE:
Ordered with value converter
Orderd without ValueConverter(ordered like it should 2017 year value on the top)
The ordering mechanism of the data table is working correctly - it's your understanding that's off I'm afraid.
When ordering in descending order, any that start with 27. will be at the top, as they're the "biggest". Within all the dates that start with 27, it'll order on the month, biggest first, and then the year.
The order mechanism doesn't realise you're ordering a date so we need to look at the Custom Sorting Plugins;
https://www.datatables.net/plug-ins/sorting/
And specifically the Date-De plugin - as that matches your date format;
https://www.datatables.net/plug-ins/sorting/date-de
An example taken from the above page;
$('#example').dataTable( {
columnDefs: [
{ type: 'de_datetime', targets: 0 },
{ type: 'de_date', targets: 1 }
]
});

How to display date from V2 OData service in a preferred format?

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?

ST datePicker and date issue

Platform is Sencha Touch 2.1.1. I am using a datPicker in a form panel as follows:
{
xtype: 'datepickerfield',
destroyPickerOnHide: true,
name : 'dateOfEvaluation',
label: 'Date of evaluation',
dateFormat: 'm/d/Y',
value: new Date(),
picker: {
yearFrom: 2013
}
},
which is being saved to as a date type in my model:
{name: 'dateOfEvaluation', type: 'date'},
If there is a value in the store it gets rendered via an itemTpl via the follwing method:
onSelectSiteGeneral: function(view, index, target, record, event) {
console.log('Selected a SiteGeneral from the list');
var siteGeneralForm = Ext.Viewport.down('siteGeneralForm');
if(!siteGeneralForm){
siteGeneralForm = Ext.widget('siteGeneralForm');
}
siteGeneralForm.setRecord(record);
siteGeneralForm.showBy(target);
}
This all works fine and dandy.
The problem is with records that do not have dates saved in them. In localStorage for a date type, the null/empty value seems to be 0, which gets displayed on my above form as '12/31/1969.' I know I could write a handler to have this display as the current date, but am sure how to proceed (I cannot use a default value: new Date(), btw, since this does not work with a value already in the data store being rendered to the form). I know I would have to add n-days to zero to get the current date, but am unsure how to get this to rerender in my form.
Any suggestions for how to get the 0th date to show up as a more realistic date, such as the current date (I will stress that default dates do not seem to work when using the above method, onSelectSiteGeneral). Grazie!

How to set the from 'day' and 'month' in datepickerfield in sencha touch 2

I am trying to do something which I think should be simple enough. I am using a datepickerfield in ST2.1 and trying to set the start date. I know I can set the year like so:
{
xtype: 'datepickerfield',
picker: {
yearFrom: newDate().getFullYear(),
yearTo: 1930
}
}
but I also want to be able to set the start day and month. Is this possible? The above produces a result like 'January 1, 2013' and that is not what I want.
If you just want to set the initial date the picker comes up with, then you just want the value config attribute of the picker.
{
xtype: 'datepickerfield',
value: (new Date()), // the value in the actual input (will also be in the picker UI)
picker: {
value: (new Date()), // use this if you DON'T want/have a value in the actual input
yearFrom: (new Date()).getFullYear(),
yearTo: 1930
}
}
Read more in the documentation (especially the "value" and "picker" config options). And here'a a Sencha Fiddle demonstrating usage.
You can create monthFrom,monthTo and dayFrom,dayTo configs. But for that you need to extend Ext.picker.Date. Create appropriate configs for those field and change createSlots method to limit month and day values.
In response to your comment, you can have reorder slots with slotOrder config in picker. Like -
slotOrder:['day', 'month', 'year']
Once you extend Ext.picker.Date you can modify certain slot as you want and then can have full day name in first slot.