Flutter store and retrieve date as YYYMM. Is Model Class the right place to do it? - flutter

For my Flutter application, I need the 'date' to be stored in Firestore as either 'YYYYMM' or 'YYYYMMDD' (Number) instead of as a Firestore Timestamp. However, to use the various date widgets, I may have to convert them into a Timestamp object to use DatePicker, etc.
So should I do this conversion in the Model Class or in the helper method that does the writing to the Firebase Firestore?

You mean you need to use the DateTime class instead of the Timestamp class?
I would use the model class. In this class define the data type for date as a Number. Create a setter method like this:
...
Number dateNumber;
...
void set date(DateTime inDate) {
// put your conversion algorithm here
dateNumber = ...
}
Later:
data.date = DateTime.now(); // for example

Related

yup - is there any way to set the default value for a string field to be something without defining it for each one

I want that every time I use yup.string(), it will add a specific default value for it
for example:
const schema = yup.object({
text: yup.string()// I want it to also do .default('some string') in the background,
});
or - another option - is there any way to set the default value after creating the scheme? something like setDefault('text', 'some string')
The closest solution I came across to solve your issue is extending your string with a custom method that implements your needs. To do that you need to use addMethod from yup:
import { addMethod, string } from 'yup';
addMethod(string, 'append', function append(appendStr) {
return this.transform((value) => `${value}${appendStr}`);
});
Now, you can use your custom method (append) and apply it to any string you want:
string().append('~~~~').cast('hi'); // 'hi~~~~'
If you want to add the custom method to all your schema types like date, number, etc..., you need to extend the abstract base class Schema:
import { addMethod, Schema } from 'yup';
addMethod(Schema, 'myCustomMethod', ...)
Extra
For Typescript
In your type definition file, you need to declare module yup with your custom method's arguments and return types:
// globals.d.ts
import { StringSchema } from "yup";
declare module 'yup' {
interface StringSchema<TType, TContext, TDefault, TFlags> {
append(appendStr: string): this;
}
}
Unknow behavior for transform method
While I was trying to extend the functionality of the date schema with a custom method that transform the date that user enters from DD-MM-YYY to YYYY-MM-DD, the custom method broke after I used it with other methods like min, max for example.
// `dayMonthYear` should transform "31-12-2022"
// to "2022-12-31" but for some reason it kept
// ignoring the `cast` date and tried to transform
// `1900` instead!
Yup.date().dayMonthYear().min(1900).max(2100).required().cast("31-12-2022") // error
To work around this issue, I appended my custom method at the end of my schema chain:
Yup.date().min(1900).max(2100).required().cast("31-12-2022").dayMonthYear() // works as expected
This issue is mentioned in this GH ticket which I recommend going through it as it's going more in-depth on how to add custom methods with Typescript.
References
addMethod
Extending built-in schema with new methods
Example of addMethod in Typescript (GH ticket)

how to create a Instant class variable in kotlin with my own timestamp

Till now i was using
val date = Instant.now(Clock.system(ZoneId.of("UTC")))
to generate the instant timestamp.
Now I need to substitute it with the date that I want to specify for example "2021-05-03T00:00:00.000Z". When i insert it as a string into the function, the idea gives me the error "Type mismatch. Required: Instant! Found: String". I can't change the function as I have no such access to it. So i need to somehow turn this date into "Instant!" class.
this is how the function that i can't change looks like
public TimeTZ(Instant timestamp, Boolean isLocal) {
this.timestamp = timestamp;
this.isLocal = isLocal;
}
val date = Instant.parse("2021-05-03T00:00:00.000Z")
Converting a string to an Instant (or other typed value) is called parsing. So use the parse method of Instant.

Models column date format

I modified my models date property to can calculate birthdays, but now when the date is loaded in my form(I use Form collective) I get it like 1979-07-17 00:00:00 right output should be 1979-07-17
protected $dates = ['geburtstag'];
public function age()
{
return $this->geburtstag->diffInYears(Carbon::now());
}
I tried to modify from model like
protected $geburtstagFormat = 'Y-m-d';
but did not help.
What I do wrong in this case
Why don't you just use $model->geburtstag->format('Y-m-d')?
You can also create a mutaror in your model like:
public function getGeburstagDateAttribute($value) {
return $this->geburtstag->format('Y-m-d');
}
and use it like this:
$model->geburtstag_date // outputs geburtstag date in 'Y-m-d' format
To set the date format in a model, use protected $dateFormat = 'Y-m-d'; inside the model.
Another way of doing it
First parse the $this->geburtstag->diffInYears(Carbon::now())
$createdAt = Carbon::parse($this->geburtstag->diffInYears(Carbon::now()));
Then you can use
$suborder['payment_date'] = $createdAt->format('M d Y');
If you don't want to store the time of birth you should change the data type in your database to date instead of from timestamp or datetime. This will solve the problem automatically since when you call the attribute on your view, this extract exactly how it's shown on database. Otherwise, if you want to keep the database unchanged you have to define a mutator in your model, like this:
public function getGeburstag($value){
return Carbon::parse($value)->toDateString();
}
This will replace the original value of geburtag attribute to its values in Y-m-d format.

How to edit date value with date type format in bootstrap

I have these codes but then the value display in the edit box is "mm/dd/yyyy"
#Html.TextBoxFor(m => m.StartDate, new { #Value = Model.StartDate.ToString("MM/dd/yyyy"), #placeholder= Model.StartDate.ToString("MM/dd/yyyy"), #class = "form-control", #type="date" })
How can I achieve something like this where the displayed date is the value from the database and not "mm/dd/yyyy"
First, don't set the value attribute directly. Razor will pretty much ignore this anyways. The value for a bound field comes from ModelState, which is itself composed of values from Request, ViewBag/ViewData, and Model, in that order. So, for example, if you want StartDate to default to "today", then you would simply populate your model with that in the action before you return the view:
model.StartDate = DateTime.Today;
Or, better, you can change the property on your model class to default to today automatically:
private DateTime? startDate;
public DateTime StartDate
{
get { return startDate ?? DateTime.Today; }
set { startDate = value; }
}
Just bear in mind that if your action happens to take a param like startDate or you set something like ViewBag.StartDate, those values will always take precedence.
Second, you're utilizing an HTML5 date input type. In browsers that support the HTML5 input types, the supplied value for a datetime, date or time, must be in ISO format. For a date, that means YYYY-MM-DD. If the value is not supplied like that, then the browser considers it garbage and discards it, leaving the control as if no value was supplied.
Also, FWIW, you don't need to prefix every member of your anonymous object with #. It doesn't technically hurt anything, but it's code smell. The # prefix exists to escape language keywords. With class, for example, you can't use it directly since it's a keyword, so you have to use #class instead. However, things like placeholder and type are not keywords, and therefore don't need an # prefix.

How to read the datetime property in sightly html (AEM 6.1)

I have one property in my cq dialog whose xtype is datetime. Value is stored like this "2016-04-11T03:00:00.000-04:00" in cq and name of the property is eventDate.
I would like to know two things here -
How can i read the date and time from this property in sightly html.
When i passing this date as the parameter in my Use class (Java class), this is getting passed as null. However, when i pass currentPage.lastModified, then i can see the date value.
Any pointers will be highly appreciated.
Not sure of the approach using sightly.
To provide an alternate solution -
You could probably used jcr api's on the node containing datetime property.
java.text.SimpleDateFormat api can be used to efficiently extract date and time.
For eg:
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
dateFormat.format(node.getProperty(eventDate).getValue().getDate().getTime())
Similarly to persist date in datetime you could probably use com.day.cq.commons.date.DateUtil api
node.setProperty(propertyName, DateUtil.parseISO8601(DateUtil.getISO8601Date(Calendar.getInstance())))
I guess the missing part is, you are not adding the use class inside your sightly. Your sightly should have this:
<div data-sly-use.eventUseObj = "com.test.models.EventModel" data-sly-unwrap />
The respective java use class should have overridden activate() method like this:
public class EventModel extends WCMUse {
private String eventDate;
#Override
public void activate() {
Calendar eventCalendar = getProperties().get("eventDate", Calendar.class);
DateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd");
eventDate = outputFormat.format(eventCalendar.getTime());
}
}
Now this date can be easily used back in sightly like this:
${eventUseObj.eventDate}
This will print the value of the date on page. There are ampty number of date patterns supported by SimpleDateFormat and you may choose the one required.
here's a simple example with javascript UseAPI, the logic should hold true with Java UseAPI
dateformater.js file :
"use strict";
//dateformatter.js
use(function () {
var formattedDate = new java.text.SimpleDateFormat(this.mask).format(this.date);
return {
formattedDate: formattedDate
};
});
and HTL (Sightly) markup example :
<h1 data-sly-use.formatter="${'dateformatter.js' # date=properties.eventDate.time, mask='dd/MM/yyyy hh:mm:ss'}">
Event date formatted: ${formatter.formattedDate}
</h1>
Sightly has built-ins that support formatting string, date and numbers. Here is how you can format date in a specific format.
${'yyyy-MM-dd HH:mm:ss.SSSXXX' # format=obj.date, timezone='UTC'}
${'yyyy-MM-dd HH:mm:ss.SSSXXX' # format=obj.date, timezone='GMT+02:00'}
The timezone parameter is optional, so if you want the time in the default timezone then you can just omit the timezone parameter.
${'yyyy-MM-dd HH:mm:ss.SSSXXX' # format=obj.date}
You can read more about it here - https://github.com/adobe/htl-spec/blob/1.3/SPECIFICATION.md#1222-dates