Using TIMESTAMPDIFF function on LocalDate in JPA Criteria query - mysql

I have to write a query calculating the time difference in years between two dates. One of the dates is fetched from the database whereas the other is a LocalDate. Following is the code I have written:
Expression<String> year = new UnitExpression(null, String.class, "YEAR");
LocalDate date=LocalDate.of(2018, 04, 30);
Expression<Integer> timeDiff = builder.function(
"TIMESTAMPDIFF",
Integer.class,
year ,
propertyListRoot.get("rentStartDate"),
date);
where UnitExpression is a custom class extending BasicFunctionExpression . However, this gives a compile time error saying
Required type Expression<?> Provided LocalDate
I researched a bit and tried
criteriaBuilder.literal(date)
This resolves the compile time error but doesn't compute the right value. What can be a possible solution? What am I missing here?

The mistake I was making was not converting the arguments of the function to Timestamp. This works fine:
Expression<Integer> timeDiff = builder.function(
"TIMESTAMPDIFF",
Integer.class,
year,
propertyListRoot.<Timestamp>get("rentStartDate"),
builder.literal(Timestamp.valueOf(month))
);

Related

Yii2 formatter asTime return different time

Why Yii2 formatter asTime method return different time from asDateTime method?
Yii::$app->formatter->timeZone = 'Asia/Tehran';
date_default_timezone_set('Asia/Tehran');
var_dump(date_default_timezone_get()); //'Asia/Tehran'
var_dump(Yii::$app->timeZone); //'Asia/Tehran'
var_dump(Yii::$app->formatter->timeZone); //'Asia/Tehran'
var_dump(Yii::$app->formatter->asDatetime('now')); //'Aug 28, 2017, 3:22:25 PM'
var_dump(Yii::$app->formatter->asTime('now')); //'10:52:25 AM' Why it's different from the top
Since 2.0.12 Yii checks if value passed to asTime() contains information about time (hours, minutes, or seconds). If not (and now does not) it takes defaultTimeZone instead of timeZone (default is UTC).
If you want time in asDatetime() to be the same as asTime() you need to set Yii::$app->formatter->defaultTimeZone = 'Asia/Tehran'; but remember it might impact other code and database records saving.
Avoid time zone conversion for date-only asDate() and time-only asTime() values.
private function formatDateTimeValue($value, $format, $type)

Laravel 4.1 - display time format from mysql column TIME

I have a column in mysql database named time_start which type is TIME.
I am trying to format the displayed time in my view from H:i:s to simple H:i, so instead of 20:00:00 i will get 20:00.
Firstly i thought i can use format() method, but it's supposed to be used with timestamps, so of course i get error Call to a member function format() on a non-object.
I'm sure it's a simple question, but i can't solve this.
-EDIT-
Forgt to mention. I am working with a many to many relationship and i'm calling my data like:
$schedule->time_start
Here i would like to show the time in H:i format, not H:i:s.
Have you tried an accessor method? I.e. in the Schedule model,
/**
* Return a truncated version of the timestamp.
* #param $value original value of attribute
* #return string truncated value
*/
public function getTimeStartAttribute($value)
{
// Input is HH:MM:SS
return substr($value, 0, 5);
// Output is HH:MM
}
Then $schedule->time_start ought to return the time in HH:MM format.

How to take Date from sql db as a single result and compare with current date

i have a complex problem with Date field. Describe what i want to do:
I have field date1 as Date in my db.
#Temporal(TemporalType.DATE)
private Date date1;
I want to take data from this field and compare with current date.
#Query("SELECT date1 FROM Table io WHERE io.date1 >= DATE_FORMAT(CURRENT_DATE, '%Y-%m-%e')")
Date findAll2();
public boolean CheckDate1(){
currentDate = new Date();
date1 = getInterimOrdersRepo().findAll2();
if(currentDate.before(date1) || currentDate.equals(date1)){
System.out.println("TRUE");
System.out.println("currentDate = "+currentDate);
return true;
}
else{
System.out.println("FALSE");
return false;
}
}
but i have an error:
result returns more than one elements; nested exception is javax.persistence.NonUniqueResultException
When method return false i want do Update field data1 with " " empty data.
I using jsf, what i must to do?
It seems that you are trying to read several values from the table into a single variable, and that is the error.
findall2 returns an array (most likely) and u should read one of it's values - try reading first one.
Furthermore, I believe that you can skip the "DATE_FORMAT" in your query, and this is a very strange way to write a code. Not clear what u are trying to achieve here

Grails insert date without time

I have a date attribute in my domain and I want to insert to MySQL without time. getting exception cannot cast string to date.Exception message:
Cannot cast object 2013-03-09 with class java.lang.String to class java.util.Date
I want to insert to the database without time.
Domain:
class Day {
Date date
static mappings = {
table name:'Days'
date type: 'date'
}
Controller:
def today = new Date()
def ymdFmt = new java.text.SimpleDateFormat("yyyy-MM-dd")
Date dateYmd = ymdFmt.format(today)
day.date =dateYmd
day.date = new Date().clearTime()
clearTime() will reset the time portion to 00:00:00
I think you wan't to look at Date.parse http://groovy.codehaus.org/groovy-jdk/java/util/Date.html#parse(java.lang.String, java.lang.String)
You can parse the date like.
String stringDate = '28/09/2010'
Date date = new Date().parse('d/M/yyyy', stringDate)
You should use java.sql.Date instead of java.util.Date.
The java.sql.Date class corresponds to SQL DATE which means it stores years, months and days while hour, minute, second and millisecond are ignored. Additionally java.sql.Date isn't tied to timezones.
For a good explanation about the two see java.util.Date vs java.sql.Date

DateField: selectedDate shows hours as 24:00:00

With a DateField component, the selectedDate.getHours returns as 24:00:00. I want it to return as 00:00:00.
Is there an easy way to do this?
Thanks!
UPDATE:
First, I set a variable in my Model that equals the selectedDate of a DateField component:
model.generalInfo.endDate = endDate_df.selectedDate;
Then I set another variable based on that value and I trace it out:
param.todate = df.format( model.generalInfo.endDate.toString() );
And this is where I see the time equal to 24:00:00
you could try something like
selectedDate.time = selectedDate.time - 24 * 60 * 60 * 60 * 1000
as a Date.time represents miliseconds since 1970 or whatever.. you substract 24 hours..
if it not works for you, you can create a new function or getter that converts it, or you can create a new mxml module, with DateField as superclass, and you can override the getHours method. tons of options to do this..
It looks like you are using the Flex DateFormatter to format the Date object. Have a look at the docs for this class, it has a formatString property that you can use to control how to output the date (or in this case the time).
If you give the DateFormatter a format string that contains "H" will output the hour in 24 hour format using the number range 1-24. If the format string contains "J" it will output the hour in 24 hour format using the range 0-23.
To get your desired output, use "JJ" in the format string, in addition to any other items. For example to output the hours, minutes, seconds:
var someDate:Date = new Date(2012, 11, 5);
var df:DateFormatter = new DateFormatter();
df.formatString = "JJ:NN:SS";
var formatted:String = df.format(someDate); // 00:00:00
Also, as #Flextras mentioned, there is Flash localization API you can use which has the added benefit of converting date/time strings to the values used by their locale. These are the DateTimeFormatter classes:
fl.globalization.DateTimeFormatter
spark.formatters.DateTimeFormatter (Flex 4)
These classes format dates into the user's locale (or one that you specifcy), and format Date objects the same way the DateFormatter does.