Flatpickr and Moment.js unexpected date format - date

I'm using the following instantiation code for Flatpickr.
$("#entry_date_time").flatpickr({
enableTime: true,
altInput: true,
defaultDate: moment().format("YYYY-MM-DD HH:MM:SS"),
dateFormat: "YYYY-MM-DD HH:MM:SS",
minuteIncrement: 1
});
The issue I'm having is that moment().format("YYYY-MM-DD HH:MM:SS"); gives me the right data but the output of $("#entry_date_time").val() is equal to
2017201720172017-JanJan-SatSat 0000:JanJan:0000
instead of the expected format I provided.
Any ideas as to what could be causing this would be great, thanks for any help!

Flatpickr has its own formating tokens that are different from the ones supported by moment. But the good thing is you can use parseDate and formatDate config options to support custom formatting tokens.
/* A custom datestring parser */
parseDate: (date: string, format: string) => Date;
/* Allows using a custom date formatting function instead of the built-in. Generally unnecessary. */
formatDate: (date: Date, format: string, locale: Locale) => string;
Example with moment.js compatible tokens
https://jsfiddle.net/armujahid/pwqhznj0/
const fp = flatpickr(".date", {
altInput: true,
dateFormat: "YYYY-MM-DD",
altFormat: "DD-MM-YYYY",
allowInput: true,
parseDate: (datestr, format) => {
return moment(datestr, format, true).toDate();
},
formatDate: (date, format, locale) => {
// locale can also be used
return moment(date).format(format);
}
});
Reference: my comment at https://github.com/flatpickr/flatpickr/issues/1549#issuecomment-537939826
Update: this snippet has also been added in official docs

Based on the output, and looking at the flatpickr docs for date and time, it seems that only single characters are expected in the format instead of multiple ? For example, the 4 Y's would explain the year being repeated 4 times, the month twice, etc.
The dateFormat that you need should probably be:
dateFormat: "Y-M-D H:i"
...however, I do NOT see a formatting option for the seconds portion of the time by flatpickr?
Update on the seconds:
There is a flatpickr feature request for the seconds capability.

Related

ngx-bootstrap datepicker output format is not ISO format

The default output format of ngx-bootstrap datepicker is not ISO format as documented.
I would welcome this format but the actual format that I get is:
Sun Aug 02 2020 19:17:00 GMT-0400 (Eastern Daylight Time)
Stackblitz Example
I know there are ways to post process the format but this format seems weird for a default output format. Does anyone have experience with this?
In vanilla JavaScript there is a 'Date' object, the default output of which gives you the line you are seeing:
Sun Aug 02 2020 19:17:00 GMT-0400 (Eastern Daylight Time)
In physical memory, your Date object is actually being stored as the number of milliseconds since "January 1, 1970, 00:00:00" which using our above line is actually "1596410220000" milliseconds.
You can read the full specifications for the 'Date' object here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Numbers_and_dates
Meanwhile, to answer your question more specifically, your date picker is not giving the output you listed but instead applying its date to a 'Date' object (newDate). You are then setting another 'Date' object (updatedDate) to be equal to the Date object assigned by your date-picker (newDate).
This is done here:
onValueChange(newDate: Date) {
this.updatedDate = newDate;
}
So in memory your updatedDate is now represented as "1596410220000" milliseconds. When you output that 'Date' object to your HTML your browser is going to use the default output for the 'Date' object, giving you:
Sun Aug 02 2020 19:17:00 GMT-0400 (Eastern Daylight Time)
So there are two solutions that you can use if you want to get that Date into a different format.
First you can call a method on your newDate to return a different formatted string. For example, if we wanted to output it as the ISO string that you were looking for originally we change this:
export class AppComponent implements OnInit {
myDateValue: Date;
updatedDate: Date;
ngOnInit() {
this.myDateValue = new Date();
}
onValueChange(newDate: Date) {
this.updatedDate = newDate;
}
To this:
export class AppComponent implements OnInit {
myDateValue: Date;
updatedDate: String;
ngOnInit() {
this.myDateValue = new Date();
}
onValueChange(newDate: Date) {
this.updatedDate = newDate.toISOString();
}
First we changed "updatedDate" to be a string object and we called the method "toISOString()" on our "newDate" (which is the Date returned from our date-picker). This gives us the ISO formatted string, which for our example is:
2020-08-02T23:17:00.000Z
The other option is to simply apply formatting to your date in your angular DatePipe. For example, if we change this:
</div>
Updated Date: {{updatedDate}}
</div>
To this:
</div>
Updated Date: {{updatedDate | date:"shortTime"}}
</div>
We would be applying the shortTime format which is "h:mm a" or for our example:
7:17 PM
You can read the full list of angular date formats here: https://angular.io/api/common/DatePipe
To summarize:
Vanilla JavaScript (not angular or ngx-bootstrap) is controlling the output format for the "Date" object here. While the output looks weird, the variable itself is not stored in that format but in milliseconds (UNIX epoch time). You can call methods on a Date object to get various formats (including ISO, UTC, etc) or you can format from angular by passing a format command along the datepipe.

Why do I get an error with Date formatting in sapUI5?

I get the error message Uncaught TypeError: Cannot read property 'group' of undefined when formatting a date in my UI5 code. I have tried using pattern and oDate.parse() but that doesn't return the date in MM/DD/yyyy HH:mm:ss format.
Here is the function that is doing the formatting
getSomeDate: function (sDate) {
var oDate = DateFormat.getDateTimeInstance({
format: "MM/DD/yyyy HH:mm:ss",
source: {
pattern: 'YYYYMMDDhhmmss'
}
});
return oDate.format(sDate);
},
The expected result is date in the format MM/DD/yyyy HH:mm:ss.
Expected date format : MM/DD/yyyy HH:mm:ss.
Source date format: new Date() object
getSomeDate: function (sDate) {
var oDate = DateFormat.getDateTimeInstance({
pattern: 'MM/dd/yyyy hh:mm:ss
});
return oDate.format(sDate);
}
If you directly want to try this out in console, you can use below code.
function getSomeDate(sDate) {
var oDate = sap.ui.core.format.DateFormat.getDateTimeInstance({
pattern: 'MM/dd/yyyy hh:mm:ss'
});
console.log(oDate.format(sDate));
}
getSomeDate(new Date());
If you want to format a date string you should use a DateTime type.
getSomeDate: function (sDate) {
var oType = new sap.ui.model.type.DateTime({
pattern: "MM/dd/yyyy hh:mm:ss",
source: {
pattern: "yyyyMMddhhmmss"
}
});
return oType.formatValue(sDate, "String");
},
if you want to use a specific pattern for formatting a date, you should use the "pattern" property. This will format your date according to the defined pattern.
The format property only allows pattern symbols. If you use a symbol that is not a valid pattern; you'll get the error "Cannot read property 'group' of undefined".
From the spec:
The format string does contain pattern symbols (e.g. yMMMd or Hms) and will be converted into the pattern in the used locale, which matches the wanted symbols best.
The symbols must be in canonical order, that is: Era (G), Year (y/Y), Quarter (q/Q), Month (M/L), Week (w/W), Day-Of-Week (E/c), Day (d/D), Hour (h/H/k/K), Minute (m), Second (s), Timezone (z/Z/v/V/O/X/x).
So if you use format the "system" tries to format the passed date according to current user settings. Using pattern will strictly follow your defined pattern.
Regards

ExtJS: Date field writes the date one day back?

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');
}
});
},

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 }
]
});

Bootstrap Datepicker, Start date Format Not set

When I am using bootstrap datepicker i need to set start state on
01/01/1930.But Format only allows when i gave count of days format.
startDate: '-31578d', (working)
But Its not working when I use direct date format. Anyone plzzz help me
startDate: '01/01/1930', (not working)
you have to add the format parameter along the startDate,
format: 'mm/dd/yyyy',
startDate:..
But Already I written code,
.datepicker({
showOnFocus: true,
showOn: "button",
format: 'mm/dd/yyyy',
startDate: '-31582d',
endDate: '+0d',
autoclose: true
})