How to create Date Format (ymd) on Firebase Realtime Database in Flutter (Dart) - flutter

I want to save the date as a timestamp or as a date format but theres no option for that type of string and if I make the date as a string/DateFormat(ymd)/or any other way it shows an error. The Code:
MyButton(
label: "Create",
onTap: () {
_validateDate();
ref.child('Time').push().set({
'Title': _titleController.text,
'Place': _subtitleController.text,
'Date': _selectedDate, //ymd or yyyy/mm/dd or any other timestamp
'Start Time': _startTime,
'End Time': _endTime
}).asStream();
_titleController.clear();
},
),
The _selectedDate format:
DateTime _selectedDate = DateTime.now();
Desired effect:
I want the date to be yyyy/mm/dd or dd/mm/yyyy

You are correct, there is no timestamp or datetime field type in FB RTDB. Also, you should not store dates as strings on databases as strings cannot be usefully processed as dates. On FB RTDB the recommended approach is to store dates as millisecondssince epoch, which is an integer.
Flutter/Dart provides methods to process this integer into DateTime variables that are then easily processed, displayed as strings, etc.
See: https://api.dart.dev/stable/2.19.2/dart-core/DateTime-class.html

Related

how to get only day number from date in flutter

I am trying to get day from date, and date comes from the api response, api response look like this
"data": [
{
_id: 6116c2e12760f71630342604,
username: 'abc',
Date: '2021-08-13',
},
{
_id: 6119ba9162069c32ccdf11c3,
username: 'acv',
Date: '2021-08-15',
}
]
i am trying to do it like this
date=Response.data['data']['Date']); //if i get date here 2021-08-15
day=date.split('-') //then will split it [2021,08,05]
day=date[2] //and then will get the day 05
but it is not working, it sends this error
type 'String' is not a subtype of type 'int' of 'index'
when i print this line day=Response.data['data']['Date']); it send same error, it is not getting date, but when i print onResponse.data it prints the api response.
please help how to do this
If your date String is in standard ISO format, simply use DateTime.parse then you can get the day easily, it would also allow you to check that the date is valid (parse will fail if date is not valid, see documentation):
String dateStr = Response.data['data']['Date']);
DateTime dateObj = DateTime.parse(dateStr);
print(dateObj.day);
If this is a custom format, you could use DateFormat from intl package (documentation):
String dateStr = Response.data['data']['Date']);
DateTime dateObj = DateFormat('yyyy-MM-dd').parse(dateStr);
print(dateObj.day);
you should use date.split("-").last and actually your index is wrong it should be day=date[2]
Let's try or you will use day[2]
day=Response.data['data']['Date']); //if i get date here 2021-08-15
day=date?.split('-').last; //then will split [05]
print(day) //and then will get the day 05

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

Flatpickr and Moment.js unexpected date format

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.

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!