Time not entered in mysql ? Java - java

I have a datetime field in mysql table and i am using JPA for persisting data but only date goes in database. Time always shows 00:00:00. What should i do?
I am not doing any manipulation with Date. All i do is to assign new Date() to a variable and store it in database.
What am i doing wrong?

Use the annotation #Temporal(TemporalType.TIMESTAMP)

Example below:
private String getDateTime() {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
return dateFormat.format(date);
}
Tips like these can be found on http://www.java-tips.org

Related

How can i enter current date and time in textbox

I want to enter the current date and time along with second in a text box ; How can I do that ?
The code what I have written is as below , but it is only entering the string value what I am passing in send keys , which is clearly indicating I am not in correct track .
Any suggestion ?
// Create object of SimpleDateFormat class and decide the format
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy ");
//get current date time with Date()
Date date = new Date();
// Now format the date
String date1= dateFormat.format(date);
// Print the Date
System.out.println(date1);
collection_title.sendKeys("date1");
In collection_title.sendKeys("date1"); you are not using your variable date1, you are using the String "date1" - there should be no quotes around date1.
It should work like this:
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date date = new Date();
collection_title.sendKeys(dateFormat.format(date));
Maybe you should try to use LocalDateTime.now() or Calender.getInstance() instead of new Date(), because the Date API methods are flawed and deprecated.

Time segment lost when I try to retrieve Date and time from SQL Database

This is what the Datetime data look like in the database
when I try to retrieve the data in my Android app, I use the following code
DateTime createDateTime = new DateTime(dataset.getDate("createDateTime"));
Log.d("Time I get is",createDateTime.toString());
at the end it only manage to return
2015-12-16T00:00:00.000+08:00
in my datalog, my time become 00:00
How can I retrieve the time too?
Please help
try using SimpleDateFormat:
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
String dateTime = sdf.format(dataset.getDate("createDateTime"));
Log.d("Time I get is", dateTime);
You can also try:
dataset.getTimestamp("createDateTime");

Convert string to a formatted date in Android

In my Java Cloud Endpoints API I have some code to get the current date and then store that date in my Cloud SQL (MySQL) database:
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
String formattedDate = df.format(c.getTime());
//formattedDate is then inserted into the database
Later on in my Android Activity I query the database and get the date back as a String that looks like:
2015-06-24 17:53:01
Now I want to format this date to display it like 06/24/2015 on the UI of my Activity. To accomplish this I do the following:
//I get a string like 2015-06-24 17:53:01 passed in from another activity
//which in-turn got it from the MySQL database
datetime = getIntent().getExtras().getString("datetime");
//first convert the string datatime to a date object
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date convertedDate = new Date();
try {
convertedDate = dateFormat.parse(datetime);
} catch (ParseException e) {
e.printStackTrace();
}
//then format that date object the way you want
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
String formattedDate = df.format(convertedDate);
//set the TextView in my Activity to display 06/24/2015
myDateTextView.setText(formattedDate);
This works. But man is it a convoluted way to do something simple. I am wondering if there is a more efficient way to do this?
You should save long value represented date into DB.
long l = c.getTimeInMillis()
and this value you should save.
answer on your question below:
Date date=new Date(l);
SimpleDateFormat df2 = new SimpleDateFormat("MM/dd/yyyy");
String dateText = df2.format(date);
System.out.println(dateText);
The simplest way is to store date in long value at DB, after that you can format to string in a very simple way.
DateFormat.format("MMM dd, yyyy", milliseconds).toString();
If you can change the source code of insertion into database, try inserting the timestamp in Long. Then conversion of timestamp to date format should be straight forward.
in Android,
final String data = DateFormat.format("MM/dd/yyyy",timestamp);

Storing Current date in database

I am having a column in my table of type TIMESTAMP.
In my servlet am writing the code to insert current date and time in this column like this :
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
String sendDate = dateFormat.format(date);
ps.setString(4,sendDate);
But it throws an Exception that:
java.sql.SQLException: [Oracle][ODBC][Ora]ORA-01843: not a valid month
What can be the reason?
Please help.
Why do you use ps.setString ?
You should use ps.setDate.
EDIT
Date dateNow = new java.sql.Date(System.CurrentTimeMillis())
ps.setDate(dateNow);
Better to use timestamp tough:
ps.setTimestamp(1, new Timestamp(System.currentTimeMillis());

How to store Java Date to Mysql datetime with JPA

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()));

Categories