How to edit date value with date type format in bootstrap - date

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.

Related

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.

One way data binding not working when using date pipe

I'm using a date object to keep track of the current date in an application.
In my view I have a one way binding like this:
<h3>{{ currentDate | date }}</h3>
And in the component, I have functions to change this date, like this:
previousMonth(){
this.currentDate.setMonth(this.currentDate.getMonth() - 1);
}
nextMonth(){
this.currentDate.setMonth(this.currentDate.getMonth() + 1);
}
But when these functions are triggered, the currentDate value doesn't update on the view.
I made sure the date object is being updated, just not on the view.
Whenever I remove the date pipe, it works.
Anyone has any idea how to fix this?
Thanks!
The value is not updating in the view because the pipes in angular are so called pure (or, stateless) by default. That means that the input will not be re-evaluated if the input object changes, but only if it's replaced.
From the documentation (see section Pure and Impure pipes):
Angular executes a pure pipe only when it detects a pure change to the
input value. A pure change is either a change to a primitive input
value (String, Number, Boolean, Symbol) or a changed object reference
(Date, Array, Function, Object).
Try the following code instead:
previousMonth(){
this.currentDate.setMonth(this.currentDate.getMonth() - 1);
this.currentDate = new Date(this.currentDate);
}
nextMonth(){
this.currentDate.setMonth(this.currentDate.getMonth() + 1);
this.currentDate = new Date(this.currentDate);
}

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

Laravel 5.1 Won't save date into database set as 00-00-00 00:00:00

I'm sending dates up using this Bootstrap datetimepicker with a format of MMM D, YYY created by MomentJS, which can't submit a different format than what is displayed to the user by default.
So on the server-side I added an mutator for the date in the model:
public function setStartDateAttribute($startDate) {
//dd(Carbon::parse($startDate)->toDateTimeString());
return Carbon::parse($startDate)->toDateTimeString();
}
Which when I dd the value looks like it should 2015-10-22 00:00:00, but it saves the date as 0000-00-00 00:00:00 or it just isn't setting the date at all, which I don't understand.
I don't want to change how the timestamps are formatted in the database so I didn't set $dateFormat and set 'start_date' in the $dates array of the Model. Thought an mutator seemed easier. The field is set to date() in the migration file, and I'm pretty sure I've done this before and it just worked. So I tried it in the my controller without the mutator and the same line works:
public function update(TournamentRequest $request, $tournamentId)
{
// Update a tournament with all fillable data, and persist to database
$tournament = Tournament::find($tournamentId)->fill($request->except('start_date'));
$tournament->start_date = Carbon::parse($request->start_date)->toDateTimeString();
$tournament->save();
return Redirect::route('dashboard.tournaments.index');
}
Why does the same code work inside the controller without the mutator setup in the Model, but not work when using the mutator?
This is how you make a setter method for your attribute. Note: you don't return anything, you just assign a value to the attribute:
public function setStartDateAttribute($startDate) {
$this->attributes['start_date'] = Carbon::parse($startDate)->toDateTimeString();
}
That's assuming you want to set a field named start_date in your table.

Struts 2 - Date instance become String

When I submit the form, input error is occur. JourneyDate is instance of 'Date'. But ,here it become String which is not accepted by the setter and getter.
<s:hidden name="JourneyDate" value="%{JourneyDate}"></s:hidden>
I want JourneyPlan as Date Type, but it become String.
Try intercepting the value before passing it to the getter/setter. For example send JourneyDateString from your form, create a Date from the String, and then pass that to your getter/setter. Something like:
public void setJourneyDateString(String journeyDateString)
{
//journeyDateString could be "2013-03-28" for example
Date journeyDate = new SimpleDateFormat("yyyy-MM-dd").parse(journeyDateString);
setJourneyDate(journeyDate);
}
The object that you've set in the value attribute will keep it's type as Date. Then you need to define corresponding setter in the action to set the value of the Date. It will convert to string if you place the value in the body of the tag.