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
Related
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))
);
Say we have a list of activities, for different clients, saved by date.
The date is saved in utc, and we know the client's timezone.
We want to know the amount of activies per day, in the client's timezone, while taking into account daylight saving times.
In mysql, we could use CONVERT_TZ(A.activity_date, 'UTC', S.timezone) As LocalDate and group by the the LocalDate.
In linq2db, we could get the offset of the timezone and add it to the utc date, however, that would not take into account DST.
Is there a method in linq2db that I have no yet found that could do this? If not, is there a way create a method that would map toCONVERT_TZ in linq2db?
A possible way to do this is to map the method CONVERT_TZ to a C# method as follows:
[Sql.Function("CONVERT_TZ", ServerSideOnly = true)]
public static DateTime? ConvertToTz(DateTime? i_Date, string i_TzFrom, string i_TzTo)
{
throw new InvalidOperationException();
}
ConvertToTz can then be called like any linq2db method, such as
...GroupBy(a => ConvertToTz(a.ActivityDate, "UTC", "America/Montreal"))
.Select(g => new {
Date = g.Key,
Count = g.Count()
})
I want to insert a Date object in mysql database, which has a Date type in the database as well. I am having problems inserting the date .
I have tried this code, but it seems codename one have a problem with it:
dateString s;
s = date.getCurrentMonth() + "/" + date.getCurrentDay() + "/" + date.getCurrentYear();
DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
Date startDate = (Date) formatter.parse(s);
Please can you tell me how to do it ?
You don't need to format it. Just use this SQL Date Object instead of Date object from java.util package.
import java.sql.Date
// Creating a date object.
Date date = new Date();
In a database, make sure the data type of attribute 'date' is selected as "Date" also, not VarChar. Simply pass this sql package Date object into the database through query. :) It will save the date in a format.
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
i have an object student. then there is a property called expiry date. this is need to be set with the database sysdate + a value(1000).
so how can i save with jpa. can't i do it on the jpa prepared statement query itself?
if i use sql.date is it exactly give the same value as when we are saving as 'sysdate'?
can't i do it with on the query itself?
other properties can be set to the object. but the problem is this expiry date as it needs the sysdate and add another value to it eg: expiry date = sysdate + 1000; how can i do it with jpa prepared statements. please reply me
What about use a seperate query to retrieve sysdate and set it to your object.
I usally create a Clock to handle this:
public interface Clock {
Date now();
}
public class HibernateClock implements Clock {
//use query to retieve the db sysdate
}
You can add it in java itself. Use calendar object to add days.
Calendar expirydate=Calendar.getInstance();
expirydate.add(Calendar.DATE, 1000);
then
expirydate.getTime() will give you expire date object.
Why do you want to use sysdate? Its syntax is database specific and also dependent on the DB-hosting machine's clock, rather than on your application-hosting machine's clock.
Easiest way is to use java.util.Date as the expiryDate's type and the value of new Date(System.currentTimeInMillis() + 1000). Use this value in the field's declaration for featuring it as default value on new Student creation or use it as the value passed to the setter when modifying an existant Student.
public class Student {
...
/**
* Using java.util.Date here. Hibernate knows to convert it automagically to java.sql.Date.
* Set default value to current time + 1 second, if this is your requirement.
*/
private Date expiryDate = new Date(System.currentTimeInMillis() + 1000);
public void setExpiryDate(final Date expiryDate) {
this.expiryDate = expiryDate;
}
...
}