I am trying to compare a SQL date with the current date.
I figured out how to compare two SQL dates but I couldn't extract the current date.
java.sql.Date xxx = new java.sql.Date(jdatechooser1.getDate().getTime());
java.sql.Date yyy = new java.sql.Date(jdatechooser2.getDate().getTime());
if (yyy.after(xxx)) {
System.out.println("ok");
}
Uses the system date instead: System.currentTimeMillis()
java.sql.Date dateToBeChecked= new java.sql.Date(jdatechooser1.getDate().getTime());
java.sql.Date systemDate = new java.sql.Date(System.currentTimeMillis());
if(dateToBeChecked.after(systemDate)){
System.out.println("ok");
}
But since it's long values you don't need to transform anything to an object and can do this instead:
if(jdatechooser1.getDate().getTime() > System.currentTimeMillis()){
System.out.println("ok");
}
At first you must create a java.util.Date object with empty constructor. Then give the long value which can be get by getTime() method, to the java.sql.Date constructor.
java.sql.Date date = new java.sql.Date(new java.util.Date().getTime());
I have some code that uses the sql.date object to get the current date in the format: yyyy-MM-dd. I want to typecast that to a Calendar object that has the same format as the sql.date.
Here is the code for the sql.date:
java.util.Date now = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date( now.getTime() );
Edit:
I want to know how to put this in a Calendar object. Is it even possible to do this?
A java.sql.Date doesn't have a format. It's just a date.
To convert it to a string, use a SimpleDateFormatter with the relevant format set - or just use toString if you definitely want yyyy-MM-dd. (Unfortunately it's unclear which time zone you should use - java.sql.Date is very poorly documented in this respect. I suspect it will use the default system time zone.)
To create a Calendar object with the given date, you can just use:
Calendar calendar = Calendar.getInstance();
calendar.setTime(sqlDate);
Again, a Calendar doesn't have a text format either - it represents a point in time in a particular calendar system in a particular time zone, but nothing about a textual representation.
Use SimpleDateFormat#format()
System.out.println(new SimpleDateFormat("yyyy-MM-dd")
.format(Calendar.getInstance().getTime()));
Java Date objects (and note that java.sql.Date is a java.util.Date) don't have "formats". They represent an instant in time.
Calendar also doesn't have a "format".
What you're asking for doesn't make sense in java.
Consider using SimpleDateFormat to format one of these things into a String:
String str = new SimpleDateFormat("yyyy-MM-dd").format(myDate);
or if you use a Calendar object (not recommended):
String str = new SimpleDateFormat("yyyy-MM-dd").format(myCalendar.getTime());
You can use the following snippet.
public class DateTest {
public static void main(String[] arg){
Calendar calendar = Calendar.getInstance();
//setting a valid date
Date date = new Date(113,07,10);
//prints the date as per format
System.out.println("Date in YYYY-MM-DD : " +date);
//sets the calendar with the date value in java.sql.Date instance
calendar.setTime(date);
//use simple date formatter to format the value in calendar instance
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
System.out.println("Date formatted from Calendar instance : "+dateFormat.format(calendar.getTime()));
}
}
Please let me know what happens!
I am using Eclipse Juno, GWT and java.
When I convert
I get the date via:
dateBoxDOB = new DateBox();
dateBoxDOB.setFormat(new DefaultFormat(DateTimeFormat.getFormat("dd-MM-yyyy")));
flexTable.setWidget(0, 1, dateBoxDOB);
dateBoxDOB.getDatePicker();
Where I enter 20/04/1961. I then need to convert it from java.util.date to java.sql.date before saving it to MySQL:
java.sql.Date sqlDOB = new java.sql.Date(dateBoxDOB.getValue().getTime());
Window.alert("Util date = " + dateBoxDOB.getValue().getTime());
Window.alert("DOB = " + sqlDOB);
java.sql.Date sqlDateArchived = new java.sql.Date(dateBoxArchived.getValue().getTime());
java.sql.Date sqlPackIn = new java.sql.Date(dateBoxPackIn.getValue().getTime());
java.sql.Date sqlPackOut = new java.sql.Date(dateBoxPackOut.getValue().getTime());
The date displayed by the window alert is -233920800000 for util and 1962-08-04 for sql.
How do I get the correct date please (i.e., 1961-04-20 from sql date)?
Also, if a date is null and exception is thrown. How do I get around this please?
This code works fine for me.
You are getting this issue because you defined the format as dd-MM-yyyy and entered date as 20/04/1961. Notice the change in format '-' vs '/'.
This may help you
Calendar cal = Calendar.getInstance();
DateFormat df=new SimpleDateFormat("dd/mm/yyyy");
String dateStr="20/04/1961";
Date date = df.parse(dateStr);
cal.setTime(date);
Date sqlDate = new java.sql.Date(cal.getTime().getTime());
System.out.println("utilDate:" + df.format(date));
System.out.println("sqlDate:" + df.format(sqlDate));
String str = "13/06/2011";
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date date = (Date)formatter.parse(str);
I guess that your Date class is actually a java.sql.Date.
What does your import statement say? Are you importing some other class (for example java.sql.Date) by accident? What does the compiler say when you remove the class cast (which should not be there)?
DateFormat.parse() returns an instance of java.util.Date and not java.sql.Date.
In order to convert from java.util.Date to java.sql.Date, I do the following:
java.util.Date fromDate = df.parse(fromdate1);
java.sql.Date sqlDate = new java.sql.Date(fromDate.getTime());
Can any body tell me how can I store Java Date to Mysql datetime...?
When I am trying to do so...only date is stored and time remain 00:00:00
in Mysql date stores like this...
2009-09-22 00:00:00
I want not only date but also time...like
2009-09-22 08:08:11
I am using JPA(Hibernate) with spring mydomain classes uses java.util.Date but i have created tables using handwritten queries...
this is my create statement
CREATE TABLE ContactUs (
id BIGINT AUTO_INCREMENT,
userName VARCHAR(30),
email VARCHAR(50),
subject VARCHAR(100),
message VARCHAR(1024),
messageType VARCHAR(15),
contactUsTime DATETIME,
PRIMARY KEY(id)
);
see in the link :
http://www.coderanch.com/t/304851/JDBC/java/Java-date-MySQL-date-conversion
The following code just solved the problem:
java.util.Date dt = new java.util.Date();
java.text.SimpleDateFormat sdf =
new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentTime = sdf.format(dt);
This 'currentTime' was inserted into the column whose type was DateTime and it was successful.
Annotate your field (or getter) with #Temporal(TemporalType.TIMESTAMP), like this:
public class MyEntity {
...
#Temporal(TemporalType.TIMESTAMP)
private java.util.Date myDate;
...
}
That should do the trick.
Are you perhaps using java.sql.Date? While that has millisecond granularity as a Java class (it is a subclass of java.util.Date, bad design decision), it will be interpreted by the JDBC driver as a date without a time component. You have to use java.sql.Timestamp instead.
Probably because your java date has a different format from mysql format (YYYY-MM-DD HH:MM:SS)
do this
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date));
you will get 2011-07-18 + time format
long timeNow = Calendar.getInstance().getTimeInMillis();
java.sql.Timestamp ts = new java.sql.Timestamp(timeNow);
...
preparedStatement.setTimestamp(TIME_COL_INDEX, ts);
mysql datetime -> GregorianCalendar
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = format.parse("2012-12-13 14:54:30"); // mysql datetime format
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTime(date);
System.out.println(calendar.getTime());
GregorianCalendar -> mysql datetime
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String string = format.format(calendar.getTime());
System.out.println(string);
java.util.Date date = new Date();
Object param = new java.sql.Timestamp(date.getTime());
preparedStatement.setObject(param);
Use the following code to insert the date into MySQL. Instead of changing our date's format to meet MySql's requirement, we can help data base to recognize our date by setting the STR_TO_DATE(?, '%l:%i %p') parameters.
For example, 2014-03-12 can be represented as STR_TO_DATE('2014-03-12', '%Y-%m-%d')
preparedStatement = connect.prepareStatement("INSERT INTO test.msft VALUES (default, STR_TO_DATE( ?, '%m/%d/%Y'), STR_TO_DATE(?, '%l:%i %p'),?,?,?,?,?)");
Its very simple though conditions in this answer are in mysql the column datatype is datetime and you want to send data from java code to mysql:
java.util.Date dt = new java.util.Date();
whatever your code object may be.setDateTime(dt);
important thing is just pick the date and its format is already as per mysql format and send it, no further modifications required.
Actually you may not use SimpleDateFormat, you can use something like this;
#JsonSerialize(using=JsonDateSerializer.class)
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/MM/yyyy HH:mm:ss")
private Date blkDate;
This way you can directly get the date with format as specified.
I still prefer the method in one line
new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime())
If using java 8 or higher , try to use LocalDateTime. That was the correct type if you are using DATETIME as mysql data type.
Below is example for conver current time to "2009-09-22 08:08:11" format
LocalDateTime currentTime = LocalDateTime.parse(LocalDateTime.now().toString(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
it works for me !!
in mysql table
DATETIME
in entity:
private Date startDate;
in process:
objectEntity.setStartDate(new Date());
in preparedStatement:
pstm.setDate(9, new java.sql.Date(objEntity.getStartDate().getTime()));