Inserting date 1 year from now into mysql Date column - java

I have a column in mysql table of type Date called expiryDate.
I want to get the date one year from now, and insert this into the expiryDate column.
I get the date 1 year from now:
import org.joda.time.LocalDate;
// expires 1 year fron now
LocalDate localDate = LocalDate.now();
LocalDate yearLater = localDate.plusYears ( 1 );
I get the error when I try to insert:
Incorrect date value: '\xAC\xED\x00\x05sr\x00\x17org.joda.time.LocalDate\xFF\xFF\xF8\x04\xD3\xE4\xEB\xB5\x02\x00\x02J\x00\x0CiLocalMillisL\x00\x0BiChro' for column 'expiryDate'
arguments:{ positional:{}, named:{expiryDate:2019-02-01,balance:50,orderId:761...
What am I doing wrong?

In MySQL, you could use DATE_ADD with INTERVAL 1 YEAR
SELECT NOW(), DATE_ADD(NOW(),INTERVAL 1 YEAR);
>>Demo<<

Using Java 8 :
Calendar cal = Calendar.getInstance();
cal.add(Calendar.YEAR, 1);
It will have no issue with MySQL driver.

Related

Convert String to Date and time in java

My program reading data from a database and I want to convert some fields to date format (date and time separately). I can do this from sql query but is it possible to do from java code.
date format in table = MMDDHHMISS (month day hour minute sec)
and these are sql queries now I'm using-
TO_CHAR(TO_DATE(DATETIMECOLUMN, 'MMDDHH24MISS'),'DD/MM/YYYY') AS MY_DATE
TO_CHAR(TO_DATE(DATETIMECOLUMN, 'MMDDHH24MISS'),'HH24:MI:SS') AS MY_TIME
Thanks in advance!
Here’s a suggestion:
DateTimeFormatter databaseStringFormatter = DateTimeFormatter.ofPattern("MMddHHmmss");
String sampleDatabaseString = "1129225145";
MonthDay myDate = MonthDay.parse(sampleDatabaseString, databaseStringFormatter);
LocalTime myTime = LocalTime.parse(sampleDatabaseString, databaseStringFormatter);
System.out.println("Date: " + myDate + ". Time: " + myTime + '.');
The above prints
Date: --11-29. Time: 22:51:45.
MonthDay is a date without a year, useful for birthdays and other anniversary dates.
Unless there are specific reasons to avoid it, I think you should rather change the datatype of your database column to datetime or similar and then retrieve LocalDateTime objects from your result set as shown in this answer. This would free you from any conversion from string to date and time in either the database query or in Java.

JPA Criteria add one day to the selected date

I have a JPA criteria that selects the max date from a table and I want to select the following day, e.g. if the query result is 1/20/17 I want the result to be 1/21/17
Here is my code:
CriteriaQuery<Date> maxDateCriteriaQuery = criteriaBuilder.createQuery(Date.class);
Root<DatesClass> datesClassRoot = maxDateCriteriaQuery.from(DatesClass.class);
maxDateCriteriaQuery.select(criteriaBuilder.greatest(datesClassRoot));
TypedQuery<Date> maxDateTypedQuery = entityManager.createQuery(amortizationsQuery);
Date maxDate = maxDateTypedQuery.getSingleResult();
I want to change the criteria to return the max date + 1
In oracle I will do it:
SELECT MAX(MY_DATE) + 1 FROM DATES_TABLE;
I will appreciate any help!
I assume you want to keep the original Date object in the database?
Than I would add 1 day to the day you retrieved from your DB:
Calendar c = Calendar.getInstance();
c.setTime(maxDate);
c.add(Calendar.DATE, 1);
Date newMaxDate = c.getTime();

compare existing month and year only in database after chosing date in java date picker

After chosing the date in date picker in java,i've got this format dd/mm/yyyy.But before inserting it in Oracle database i want first to compare only if month and year exist,not the day.If the month and year is already recorded i don't insert, if not,i insert it and reset the only the day to the first day of the month,but keep the month and year as they are.My program is only concerned by date and month,that why i want to know how to compare only the two before inserting.I've tried to do the following code:
Resultset res = st.executeQuery("select count(*) as rowCont from doc_arriv where month_arv=to_char(chosen_date,'mm/YYYY');
res.next();
But it isn't comparing
calendar=java.util.Calendar.getInstance();
calendar.setTime(chosen_date);
//we must add 1 here beacause Calendar intialise months by zero
int month= calendar.get(Calendar.MONTH)+1;
//we get the year
int year= calendar.get(Calendar.YEAR);
String req = "SELECT count(*) from doc_arriv where
EXTRACT(month FROM month_arv) = " + month +
"and EXTRACT(year FROM month_arv)= " = year ;
Resultset res=st.executeQuery(req);
res.next();
//continue your code here you must calculate the result of the request if more than 1 you insert else you dont insert and for change the day to the first day of month you must execute the code
calendar.set(Calendar.DAY_OF_MONTH, 1);
chosen_date= calendar.getTime();
//good luck
First of all better use a PreparedStatement. Then simply compare the dates of the with the first day of the month and the first day of the next month (assuming the type of the month_arv column is DATE):
LocalDate date = ...
LocalDate startOfMonth = date.withDayOfMonth(1);
LocalDate startOfNextMonth = startOfMonth.plusMonths(1);
// save for later use (insertion)
Date sqlStartOfMonth = Date.valueOf(startOfMonth);
PreparedStatement statement = connection.prepareStatement("SELECT COUNT(*) FROM doc_arriv WHERE month_arv >= ? AND month_arv < ?");
statement.setDate(1, sqlStartOfMonth);
statement.setDate(2, Date.valueOf(startOfNextMonth));
ResultSet res = startment.executeQuery();

how to compare a given date with current date in sql

i want to write a query to compare a given date with today date with timestamp.
given date can be the today date, if the date is same it will compare the time.
select * from abcTable where submitDate <= now();
here its comparing only the date not the time.
submitDate is anydate which is in the db table.
Firstly, you have specified that column submitDate is of datatype Date while, as per your question its datatype should be Timestamp.When the datatype of submitDate column is Date, there is no reason to even compare the time.
However if you need to still want to compare the submitDate with current timestamp, you can do it this way:
select * from submitDate where date_format(submitDate,'%d/%m/%y %T') <= now();
Edit: The above query is for Mysql
I think you should try:
GETDATE() --2017-01-17 08:19:28.403
you can get day, month and year separately by doing:
select DAY(getdate()) --17
select month(getdate()) --1
select year(getdate()) --2017
if you are on sql server 2008, there is the DATE date time which has only the date part, not the time:
select cast (GETDATE() as DATE) --2017-01-17
OR you you can try:
select * from abcTable where submitDate <= CAST(CURRENT_TIMESTAMP AS DATE);
OR
select * from abcTable where submitDate <= cast((now()) as date);

How to convert sql date to Joda Datetime?

I'm working with date sql and getDay() returns the day of the week represented by this date. The returned value (0 = Sunday, 1 = Monday, 2 = Tuesday, 3 = Wednesday, 4 = Thursday, 5 = Friday, 6 = Saturday)
//type of dateStart and dateEnd is java.sql.Date
//type of DateTime is joda.time.DateTime
public static Date[][] getListPeriod(Date dateStart , Date dateEnd){
DateTime start = new DateTime(dateStart.getYear()+1900,dateStart.getMonth()+1,dateStart.getDay(), 0, 0, 0, 0);
Example : value of the dateStart : 2015-07-01
and dateStart.getDay() return 2015-07-03 (3 = Wednesday)
I want dateStart.getDay() get this value 1
How about using new DateTime(dateStart.getTime()) ?
To get the day (of the month) from a java.sql.Date, you have to use getDate. This method is inherited from java.util.Date and deprecated. The correct way to get parts from a date is to use a Calendar.

Categories