Insert date and get it in wrong format - java

I insert the current date in a table. I have a method to get the current datet:
private static java.sql.Date getCurrentDate() {
java.util.Date today = new java.util.Date();
return new java.sql.Date(today.getTime());
}
Or in some cases I get the date from a from in a String format e.g. 2016-10-12 and then I call this method with action.setTodayInfo(session, getCurrentDate()); to insert to a table the date and some Boolean variables
public void setTodayInfo(HttpSession session, Date date)
throws SQLException, ClassNotFoundException {
System.out.println("Initialize today's info...");
String sq = "INSERT INTO IsSELECTED (date, morning, noon, night) VALUES (?, ?, ?, ?)";
try {
Class.forName(typeDB);
c = DriverManager.getConnection(path);
stm = c.prepareStatement(sq);
PreparedStatement stm = c.prepareStatement(sq);
stm.setDate(1, date);
stm.setBoolean(2, FALSE);
stm.setBoolean(3, FALSE);
stm.setBoolean(4, FALSE);
int rowsAffected = stm.executeUpdate();
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (stm != null) {
stm.close();
}
if (c != null) {
c.close();
}
}
}
when I look in the table the date field has this 1434473268231 and not the current day in format like 2015/06/16.. The table format is:
CREATE TABLE "IsSELECTED"(
"date" DATETIME PRIMARY KEY NOT NULL DEFAULT (CURRENT_DATE) ,
"morning" BOOL NOT NULL DEFAULT (0) ,
"noon" BOOL NOT NULL DEFAULT (0) ,
"night" BOOL NOT NULL DEFAULT (0)
)

There is no need to worry about the format of the date when storing it. The database will simply store the date instance and you can use one of its functions to format it on retrieval.
You could also use Java to format the date on retrieval using SimpleDateFormat

Divide 1434473268231 by 24*60*60*1000*365 and you'll get 45, which is the number of the years since the start of the epoch 1970.
This means that the value you are seeing is the number of milliseconds since Jan 1, 1970.
That should be OK - usually date values are internally stored as milliseconds since some agreed-upon point in time.

According to this: https://www.sqlite.org/datatype3.html SQLLite doesn't really have a special type for DATETIME.
"Applications can chose to store dates and times in any of these formats and freely convert between formats using the built-in date and time functions."

Related

java-How should one pass a date value to MySQL?

I have a column field called StartDate in MySQL of Date datatype. In my application, I defined a way to show the current date onn my page like this.
String today = CoreUtil.parseDate(new Date());
This basically returns the date in YYYY-MM-DD format and stored it in a string which is fine.
Now, I would like to pass this value into a function that inserts the value to the column StartDate.
The function I declared is as follow:
public void insert_update(String nodeid,String ts,Date startdt,Date enddt,int enable)
I am calling this function and passing the value today to it like below:
fileFacade.insert_update(...,....,today,....,...);
Now I am not an expert in this date thingy and seeing it wouldn't allow me to pass the value as I defined it as Date parameter, how should I handle this issue?
Should I convert it back to Date format and pass the value or does MySQL allow insertion of string value into a Date datatype column?
I just want to store the value in my table in YYYY-MM-DD format.
edit:
My function:
public void insert_update(String nodeid,String ts,Date startdt,Date enddt,int enable){
try {
// UrlLink attr = em.find(UrlLink.class,n);
String sql="UPDATE urllink SET STARTDT="+startdt+",ENDDT="+enddt+",ENABLE="+enable+"WHERE URL='f0="+nodeid+"&ts="+ts + "'";
em.createNativeQuery(sql).executeUpdate();
}catch (Exception e) {
e.printStackTrace();
}
}
You should not try to convert String into a Date in order to insert it into a table. You can use date type as is using preparedStatement, e.g.:
Date date = new Date();
PreparedStatement pStmt = connection.prepareStatement("<query>");
pStmt.setDate(1, date);
Here's the javadoc.
Update
If the purpose here is to display the date in specified format then I would strongly recommend storing the date as DATE in MySQL in format it while querying. The decision of how we store the date should not be driven by how it needs to be displayed on Front End as we might need different date formats to be displayed across multiple User Interfaces.
Pass String date in method parameter instead of Date type and then format that date type like this:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd",Locale.ENGLISH);
formatter.parse(date)

Localdate.format, format is not applied

I have a DatePicker in my FXML and I need the Date to insert it into my SQL-Database. I want to format my Date but it doesn't work.
LocalDate localDate = purchased_at.getValue();
localDate.format(DateTimeFormatter.ofPattern("dd.mm.yyyy"));
This is the Error I get.
Caused by: java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: MinuteOfHour
I'm still kind of a beginner. I had Java for the past 3 or 4 months now. I'm trying my best to improve.
Don’t format your date for insertion into your SQL database. Assuming that your database column has datatype date and you are using at least Java 8 and at least JDBC 4.2, just pass the LocalDate to your PreparedStatement as it is:
PreparedStatement insertStmt = myConnection.prepareStatement(
"insert into my_table(purchase_date) values (?)");
insertStmt.setObject(1, purchaseDate);
Your JDBC driver will take care of the rest. If using JPA, your JPA implementation will take care of it too.
If your column has char type (for example varchar(10)) and you cannot change it, don’t invent your own format for it. Store the date in ISO 8601 format. LocalDate.toString() produces this format.
String formattedDate = purchaseDate.toString();
System.out.println(formattedDate);
In my case output was:
2017-11-29
As an aside, for presentation to your user you shouldn’t invent your own format either. Rather rely on the built-in formats in Java. For example:
Locale turkish = Locale.forLanguageTag("tr");
DateTimeFormatter dateFormatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT)
.withLocale(turkish);
String formattedDate = purchaseDate.format(dateFormatter);
System.out.println(formattedDate);
Output:
29.11.2017
What went wrong in your code?
There are two things wrong:
You used lowercase mm. This means minute of hour, and since a LocalDate doesn’t have a time of day in it, it threw the exception you saw. The message you got is pretty precise:
Unsupported field: MinuteOfHour
Instead you may use uppercase MM for two-digit month.
You need to pick up the format in the String returned from the format method. The LocalDate is immutable and therefore not affected by the method call. Also it cannot have a format in it. It’s just a date in the calendar.
Links
Wikipedia article: ISO 8601
Insert & fetch java.time.LocalDate objects to/from an SQL database such as H2
How to format LocalDate object to MM/dd/yyyy and have format persist (TL;DR: you cannot)
I had to use a String converter for my Datepicker.
public String changeformat(DatePicker date) {
date.setConverter(new StringConverter<LocalDate>() {
String pattern = "MM.yyyy";
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern(pattern);
{
date.setPromptText(pattern.toLowerCase());
}
#Override
public String toString(LocalDate date) {
if (date != null) {
return dateFormatter.format(date);
} else {
return "";
}
}
#Override
public LocalDate fromString(String string) {
if (string != null && !string.isEmpty()) {
return LocalDate.parse(string, dateFormatter);
} else {
return null;
}
}
});
return null;
}
It worked perfectly fine. I had to use a parameter since I'm currently using 5 Datepickers.

Set Date Param in Mysql from Java

I have jsp page view and in java and I am getting datepicker value in Java
Using this : LocalDate localDate = datePicker.getValue();
I am not able to set this value using query in Mysql database where type is date in my table of column date of birth
Assuming you are using PreparedStatement, You just need to convert LocalDate into sql.date and set it in, e.g.:
LocalDate localDate = datePicker.getValue();
Date date = Date.from(localDate.atStartOfDay().toInstant(ZoneOffset.UTC));
PreparedStatement pStmt = //your preparedstatement
pStmt.setDate(1, new java.sql.Date(date.getTime()));
The date format for mysql insert query is YYYY-MM-DD
example:
INSERT INTO table_name (date_column) VALUE ('YYYY-MM-DD');
so change your java code to generate such YYYY-MM-DD string
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
// ...
LocalDate date = datePicker.getValue();
if (date != null) {
display.setText(formatter.format(date));
} else {
display.setText("");
}

Convert a String date to Long Date and update rows in derby database

In my java application I am trying to update some rows with long date value. I've pasted my codes below. Here the table name is "CASHSELL" The columns are "DATE VARCHAR(20) and "DATES BIGINT".
String query = "SELECT DATE, DATES FROM CASHSELL";
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
try{
conn = new connection().db();
stmtt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
rs = stmtt.executeQuery(query);
while (rs.next()){
String dat = rs.getString("DATE");
Date d = (Date) sdf.parse(dat);
long longDate = d.getTime();
rs.updateLong("DATES", longDate);
rs.updateRow();
conn.commit();
}
}
catch(SQLException | ParseException ex){JOptionPane.showMessageDialog(null, ex);
}
finally{try{rs.close(); conn.close(); stmtt.close();}catch(SQLException ex){} }
This method is not working anyway. What is the mistake I am making here? There is no error message also? Am I missing something? Or is it not the proper way to update with JDBC? Is there any other way, so that I can Update 1,00,000 rows by converting the string date to long date?
I am working in Derby Database.
No need for a loop or the SELECT at all.
update CASHSELL
set dates = {fn TIMESTAMPDIFF(SQL_TSI_SECOND, timestamp ('1970-01-01 00:00:00'), "DATE") } * 1000;
TIMESTAMPDIFF will return the number of seconds between 1970-01-01 and the value of the DATE column. As the long value of a java.util.Date is the number of milli seconds since then, you need to multiply the result with 1000.
So the above statement will update the dates column to the corresponding long value of the DATE column.
But I don't understand why you want to do that. Storing a derived value is usually not a good idea. You can always calculate that value "on-the-fly" when retrieving the data from the table.
Btw: DATE is a horrible name for a column. Firstly because it's a reserved word and can lead to a lot of confusion. Secondly because it does not document the data model. Is that a "due date", a "valid from date", a "valid until date", a "birthdate" ....
And DATES is just as confusing. You should have named it milliseconds or something similar.

Java & SQL comparing dates

I am trying to get client arrival date and compare it with my SQL database to see if in my data base the same date exists. however i receive the following error: The operator > is undefined for the argument type(s) java.lang.String, java.lang.String
P.S I need to compare it via java not using sql query
public void makeNewReservation() throws ParseException {
// Enter informations
System.out.println("Date of arrivel?");
Scanner in = new Scanner(System.in);
String date_entree = in.next();
System.out.println("Date of exit? dd/MM/yyyy");
String date_sortiee = in.next();
calculateDaysDifference(date_sortiee, date_entree);
public void calculateDaysDifference(String date_entree, String date_sortiee) throws ParseException{
ConnectionMySQL myConnection=new ConnectionMySQL();
Connection conSQL=myConnection.startDBConnection();
boolean connectionOK=myConnection.checkConnection(conSQL);
String query = ("SELECT `START_DATE`,`END_DATE` FROM `room_booking");
//if everything is fine with the connection, i try to execute a query
if (connectionOK){
try{
ResultSet mesResultats=myConnection.executeQuery(conSQL, query);
//the while loop is just for me to check the dates
while (mesResultats.next()) {
System.out.println("START_DATE: "+mesResultats.getString(1)+" END_DATE : "+ mesResultats.getString(2));
if (date_entree > mesResultats.getString(1){
System.out.println("cant reserve room room reserved already");
}
}
// je ferme la connexion
conSQL.close();
}
catch(SQLException e){
e.printStackTrace();
}
}
my data base
You need to compare 2 Dates
1) Convert the input String into Date
SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
java.util.Date d=df.format(/*date String*/);
NOTE: df.format will throw parseException if the String format does not match "yyyy-MM-dd" . I leave it upto you to make sure the date string is of the specified format.
2)get Date from sql query
java.util.Date sqlDate=new java.util.Date(resultset.getDate().getTime());
NOTE : resultset.getDate() will give you java.sql.Date class's object.
3) Compare 2 dates
try this logic
Date date1=new Date(df.parse(mesResultats.getString(1)));
Date date2=new Date(df.parse(mesResultats.getString(2)));
int status=date1.compareTo(date2); //compareto is a function defined for date
if status==0 print same date
if status<0 print date1 is older then date2
if status>0 print date1 is newer then date2
[Update after comment]
DateFormat df = new SimpleDateFormat("Format of your date goes here");

Categories

Resources