i have one Date field to save date into DB and date field should be in Date and Time format (MM/dd/yyyy HH:mm:ss)..
for that i am using DateFormat to convert the current Date as,
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date date = new Date();
String DateStr = dateFormat.format(date);
Here the result will be in String format and to save as Date object in DB using Hibernate i have to again convert that date string into Date obj as,
Date newdate = dateFormat.parse(DateStr);
So my question was, is there any better way to return the current Date along with Time as Date obj..
and also does Hibernate will automatically convert the String to Date, if we set the field type as String and by annotating as,
#Temporal(TemporalType.DATE)
#Column(name = "REQUESTED_DATE")
public String getRequestedDate() {
return requestedDate;
}
thanks.
Change your annotation to:
#Temporal(TemporalType.TIMESTAMP)
This will persist the time to the DB.
You can use java.sql.Date to store values that map to SQL DATETIME (or the MySQL variant). I do not understand why you say "by using new Date(),i [sic] will be getting only date not time". That is not correct. However, it is not optimal. You can also use java.sql.Timestamp. You get the best results when you use java.util.Calendar.
I found http://www.developerscrappad.com/228/java/java-ee/ejb3-jpa-dealing-with-date-time-and-timestamp/ in less than five minutes of Googling, and it answers your question pretty well.
#Temporal(value = TemporalType.TIMESTAMP)
Date date;
you can store date object directly into database that hibernate offers you. So, lets get rid of string.
Related
I'm using JPA and I want to store the date in this format dd/MM/yyyy HH:mm:ss
So I create a function
public static String getNowDate() {
Date date = new Date();
final DateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
return sdf.format(date);
}
The problem is that this returns a String and I need a date.
#Temporal(TemporalType.TIMESTAMP)
private Date creationDate;
How do I make this work so I can save date and time exactly like that?
I know a easy solution is to declare creationDate as String. Is this too bad?
There is a problem with the premise to your question. Ideally, your current timestamp will be stored in a SQL database, in some sort of date column, and not as text. Since you are using JPA, backed by JDBC, you should just be inserting a date type. So, something like the following should work:
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
// or maybe just
Date now = new Date();
Then, just let JPA worry about how to martial the current timestamp into your database table. If you really need to format your timestamp as shown, then worry about this in your Java code somewhere.
I have date saletime as 2/25/14 22:06 I want to store it in oracle table in the yyyy-MM-dd hh:mm:ss. So I wrote following java code
Date saleTime = sale.getSaleTime();
logger.info("DateTime is "+saleTime);
SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date saleTimeNorm = formatter.parse(formatter.format(saleTime));
logger.info("DateTime after Formating "+saleTimeNorm);
Timestamp oracleDate = new Timestamp(saleTimeNorm.getTime());
logger.info("New Format Inserting :"+oracleDate);
sale.setSaleTime(oracleDate);
But this seems to be giving :0014-02-25 22:06:00.0
Any suggestions ?
Your getSaleTime() method somehow regards "14" as a four-digit year, and returns the year 14.
After you have executed getSaleTime(), you already have a Date variable; there is no need (and no use) in converting it to a different output format and re-parsing the result. The Date you get from the calls to format() and parse() will be the same one you started with.
You can create your Timestamp using getTime() on the result of the call to getSaleTime(). That will be correct once you change getSaleTime() so that it returns the date in the correct year.
Something must be wrong in your sale.getSaleTime() method. Because the following code working as needed.
Date saleTime = Calendar.getInstance().getTime();
SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date saleTimeNorm = formatter.parse(formatter.format(saleTime));
Timestamp oracleDate = new Timestamp(saleTimeNorm.getTime());
System.out.println(oracleDate);
//2014-05-13 03:58:53.0
I am using Eclipse to do a college project on Java. I realized that java does not have a built in date selector like C#, so I downloaded and added JDateChooser. I tried to retrieve the chosen date but it failed:
String Date = dateChooser.getDate(); //I want to the date to be retrieved as string
Any ideas? Is there some kind of initialization that I must do?
Retrieve the date that the user selected by calling getDate(), which returns a Date object. Then convert that object into a String by calling SimpleDateFormat.format():
Date d;
SimpleDateFormat sdf;
String s;
d = dateChooser.getDate(); // Date selected by user
sdf = SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); // Or whatever format you need
s = sdf.format(d); // Viola
See also: Question 5683728
If I have the right component, the Java Docs show that the getDate method returns Date
getDate
public java.util.Date getDate() Returns the date. If the
JDateChooser is started with a null date and no date was set by the
user, null is returned. Returns: the current date
String dob =new SimpleDateFormat("dd-MMM-yyyy").format(jDateChooser1.getDate());
One of the fields which I extract from a database is a date in string format and I need to convert it into a date type to compare with another date.
How do I do this please? Everything I have tried so far gives me an error of java.util.Date cannot be cast to java.sql.Date and this is attempting the following example;
simpledateformat-gives-java-lang-classcastexception-java-util-date
An example of the date extracted in string format is "2012-10-15 09:00:29.157". I think the format to declare is yyyy-MM-dd HH:mm:ss.SSS but not sure.
Thanks
You can create a java.util.Date from java.sql.Date as follows:
java.util.Date date = new java.util.Date(resultSet.getDate("Column").getTime());
Alternatively you can convert the java.sql.Date to either java.util.Calendar or Joda library's DateTime and perform comparisons.
If you are looking at parsing date, then java.text.SimpleDateFormat is your friend.
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
java.util.Date date = format.parse("2012-10-15 09:00:29.157");
It simply means you are assigning java.util.Date in java.sql.Date
From your example you have to do following :
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
java.util.Date date = (java.util.Date)formatter.parse(""2012-10-15 09:00:29.157"");
Convert to Date as Vikdor showed. then get the long timestamp = date.getTimestamp();
Now this long value is millisecons since 1970 utc. just compare by this value.
Here is my problem:
I have a user input a date like: 2012-12-24 (string)
I concatenate a time to that string, and convert to java.util.Date
My code looks like:
String tempstartdate = startdte; //startdte is the string value from a txtfield
tempstartdate += " 00:01:00";
String tempenddate = startdte;
tempenddate += " 23:59:59";
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
java.util.Date validstartdte = null;
java.util.Date validenddte = null;
validstartdte = df.parse(tempstartdate); //validstartdte is a util.Date (and works)
validenddte = df.parse(tempenddate);
My problem is, when I take that util.Date and want to make it an sql.Date:
java.sql.Date sqlstartDate = new java.sql.Date(validstartdte.getTime());
java.sql.Date sqlendDate = new java.sql.Date(validenddte.getTime());
It will not give me the timestamp I assigned, it will only return the date in the form yyyy-MM-dd (such as 2012-12-23).
WHY!? I'm so frustrated.
Note: I noticed that when I used breakpoints, I was able to expand sqlendDate and see there is a value in there called cdate that returns: 2012-12-12T23:59:59.000-0500
The database I'm using is PostgreSQL.
Please help! Much appreciated.
java.sql.Date doesn't have the time.
Use java.sql.Timestamp instead.
I might be very late to answer this question but I think it might be helpful.
As stated by 'Felipe Fonseca', I converted the util date to sql date as follows:
public static java.sql.Timestamp convertToSqlDateTime(Date utilDate){
return new java.sql.Timestamp(utilDate.getTime());
}
Normally, java.sql.Date only returns Date value and time will be discarded. So, in order to get time also, java.sql.TimeStamp must be used.
TimeStamp Constructs a Timestamp object using a milliseconds time value. The integral seconds are stored in the underlying date value; the fractional seconds are stored in the nanos field of the Timestamp object.
For this purpose, utilDate.getTime() is used to return the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date Object.
If we want only java.sql.Date, we can do:
public static java.sql.Date convertToSqlDate(Date utilDate){
return new java.sql.Date(utilDate.getTime());
}
I have completely given up on using Java's standard Date classes, for exactly the reasons you list.
I've been using Joda Time for a while now, and have found it a lot simpler.