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

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

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.

How to convert/parse a string to a date object with Thymeleaf?

I am trying to parse string ISO dates (like "2016-01-01") to be able to format them.
#dates and #temporals seem to be only able to format Date/LocalDate/LocalDateTime objects.
For instance I want Thymeleaf to display "January 1st, 2016" when it is passed "2016-01-01".
Thanks.
Take a look the section Reformatting dates in our home page of the reference documentation.
....
...we can do just this:
WebContext ctx =
new WebContext(request, response, servletContext, request.getLocale()); ctx.setVariable("today",
Calendar.getInstance());
templateEngine.process("home", ctx, response.getWriter());
…and then perform date formatting in the view layer itself:
<p> Today is: <span th:text="${#calendars.format(today,'dd MMMM yyyy')}">13 May 2011</span> </p>
I ended up implementing my own dialect containing utility functions such as parseISODate(String date) which returns a LocalDate then in the HTML I can do
th:text="${#temporals.format(#myDialect.parseISODate(someStringISODate), 'dd/MMM/yyyy')}"

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.

grails change Date format in gsp view

When I try to use date format tag in gsp view to change the format of my date but it doesn't work.
This is my code:
class MyDate {
Date date
}
MyDateController:
....
def unixSeconds = params["date"].replaceAll("\"", "") as long //params["date"]="1386157660"
Date date = new Date(unixSeconds*1000L)
myDateInstance = new MyDate(date:date)
....
gsp View:
${myDateInstance.date.format('yyyy-MM-dd HH:mm')}
The format that I have is 2013-12-04 12:47:40.0 instead of 2013-12-04 12:47
Afaict, that shouldn't happen and I can't see how it is happening...
Are you sure that's the line of code that's generating the output you're seeing?
You could try the Grails formatDate tag in its place:
<g:formatDate format="yyyy-MM-dd HH:mm" date="${myDateInstance.date}"/>
You can use "formatDate" in value attribute like following
<g:textField name="saleDate" value="${formatDate(format:'dd-MM-yyyy',date:saleItem?.saleDate)}"/>
In addition to #tim_yates's answer above, there is another point I want to add:
I observed that if type and style are given, format is not used. I think they work as alternatives for each other. Also, using format would be beneficial as the Date string format could differ on different operating systems.

How to pass Date values as params in Grails

I have seen a few posts related to using the g:datePicker in Grails. Using this it looks like you can just pick the value off the params like so params.myDate.
However, when I try to do something like this in my view:
view:
<g:link controller="c" action="a" params="[fromDate:(new Date())]">
controller:
def dateval = params.fromDate as Date
The date is not parsing out correctly. Is there something else I should be doing in the view to make the date 'parsable' by the controller. I've looked around and haven't found this in any posts where datePicker is not used.
I prefer to send time instead of dates from the client.
<g:link controller="c" action="a" params="[fromDate:(new Date().time)]">
And in action I use the constructor of Date that takes time.
def date = params.date
date = date instanceof Date ? date : new Date(date as Long)
I have created a method in DateUtil class to handle this. This works fine for me.
When the parameters are sent to a controller they are sent as strings. The following won't work
def dateval = params.fromDate as Date
Because you haven't specified what date format to use to convert the string to a date. Replace the above with:
def dateval = Date.parse('yyyy/MM/dd', params.fromDate)
Obviously if your date is not sent in the format yyyy/MM/dd you'll need to change the second parameter. Alternatively, you can make this conversion happen automatically by registering a custom date editor
Whatever is sent from view is a string so params.fromDate as Date does not work.
In grails 2.x a date method is added to the params object to allow easy, null-safe parsing of dates, like
def dateval = params.date('fromDate', 'dd-MM-yyyy')
or you can pass a list of date formats as well, like
def dateval = params.date('fromDate', ['yyyy-MM-dd', 'yyyyMMdd', 'yyMMdd'])
or the format can be read from the messages.properties via key date.myDate.format and use date method of params as
def dateval = params.date('fromDate')