I want to compare a dateTime Object with the today date.
This is my date Object
<f:format.date format="d.m.Y - H:i:s">{article.validFrom}</f:format.date>
I want to make a condition, if the date Object is bigger than the current day. I will do something.
Can anybody help me ?
Convert the date to an unix timestamp using format="U" and compare them. You need to add a variable which contains the current date.
In your controller add
$this->view->assign('date_now', new DateTime());
// or for TYPO3 >= 6.2
$this->view->assign('date_now', new \DateTime());
then in your template use following
<f:if condition="{f:format.date(date: article.validFrom, format: 'U')} > {f:format.date(date: date_now, format: 'U')}">
Date is valid
</f:if>
EDIT:
The other way (and I think is the better way) is to add a new method to your model which checks this. Example:
Classes/Domain/Model/Article.php
class Article extends \TYPO3\CMS\Extbase\DomainObject\AbstractEntity {
/**
* #return boolean
*/
public function getDateIsValid() {
return ($this->getValidFrom() > new DateTime());
}
}
then you can simply use
<f:if condition="{article.dateIsValid}"></f:if>
Related
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.
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')}"
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
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.
I have to check a condition on date whether a date field of a entity is in range of another two sets of date from other entity
First Entity :
1. id
2. name
3. date
Second Entity ;
1. id
.
.
.
.
17 : Start Date
18 : End Date
I have to check whether the date field of first entity is in range of Start Date and End Date of second entity.
e.g.
(t1.date>= t2.Start Date and t1.date <= t2.End Date)
Problem is that, there are some row where t2 is null.. if it is null, then second condition return true.
My Attempt
PriorAuthorizationLogVO( cardid == $paidClaimVO.cardholderId, ruleType == 'INCL' , $paidClaimVO.time>=etime , (ttime==null || (ttime!=null && $paidClaimVO.time<=ttime))
But, i am not able to confirm whether it is working....
Please help.
You could add that check for date between the range of dates in either a static helper method or within one of your entities. In my opinion this will make your rules more readable and you can easily write unit tests for the date check method.
Option 1 - Static helper method
Create a class for having static helper methods, something like this
public class DateUtils {
private DateUtils() {} // Cannot be initialized
public static boolean dateInRange( Date toCheck, Date min, Date max ) {
// Add null checks here
// Use Date#before(Date) and Date#after(Date) for checking
return true|false
}
}
Your rule would then be like
import static DateUtils.*
rule "date in range"
when:
dateInRange( e1.date, e2.start, e2.end )
then:
// logic
end
Option 2 - Method within fact/entity
Create the check method inside one of your facts. In which entity to put this depends on your use case, the information you've given does not specify this yet. I think you can figure out the best place by yourself. Anyway, the code would be something like this
public class Entity1 {
Date date
}
public class Entity2 {
Date start
Date end
public boolean entity1InRange( Entity1 e ) {
// null checks
// Use the Date#before() and Date#after() as above
}
}
And the rule
rule "date in range"
when:
e2.entity1InRange( e1 )
then:
// Logic
end