How to declare a variable which holds Timestamp value from database? - java

I have a timestamp in my database. I want to fetch it from database using JAVA and display it to the user. How do I declare timestamp in JAVA? I am using Date, but it is storing yyyy-mm-ddd format. I want yyyy-mm-dd hh:mm:ss format.
Date date = siteBean.getAlertTime();
I want the date variable to hold yyyy-mm-dd hh:mm:ss
How can I do that?

You should consider working with Calendar, as Date is deprecated. The JavaDocs explains nicely how to replace your code with Calendar-methods.

Consider fetching the timestamp from your ResultSet as a String. You can manipulate the String within Java with the help of SimpleDateFormat.

Related

Set date format dd/mm/yyyy in SQL table

I want to save the dates in my database in the dd/mm/yyyy format, because I want to import the table that contains them in a JTable (Java SE) and I want to display them in this format. Is it possible to directly save the date on my database in this format or I must do it in another way? My DB is write in SQL and I use MySQL.
Date are dates. It doesn't exists a format for dates.
What you can obtain is a string with a particular format from the date.
Note that the format probably is not dd/mm/yyyy but dd/MM/yyyy because mm is for minutes, not for months.
So basically you have two possibilities:
Save dates as Date and retrieve them as string with the requested format
Convert dates to strings and save them as formatted strings (VARCHAR for example)
To convert a Date to a String in MySql you can use the function DATE_FORMAT
If you like to convert them in java you can use a SimpleDateFormat
There is no possibility to save the date in the specified format but yes you can set the type of that field as String (in MySql varchar) and you can save whatever you want.
You can't do it,
or else you have to use VARCHAR or CHAR, but thats not recommended.
save the date in DATE datatype with format yyyy-mm-dd.
don't mess with it.
When you fetch the records, use DATE_FORMAT function to convert it into your format. (if you use MySQL)
like
SELECT DATE_FORMAT(CURDATE(), '%d-%m-%Y');
in your case
SELECT DATE_FORMAT(< your_date_field >, '%d-%m-%Y');
Use DATE_FORMAT function to change the format of a date in MySQL.
SELECT DATE_FORMAT(CURDATE(),'%d/%m/%Y')
SELECT DATE_FORMAT(column_name,'%d/%m/%Y') # FROM tablename
Refer to documentation for more details.

Converting String date to SQL Date

I have a string date in the format DD/MM/YY (16/07/13)
How do I convert this string date to SQL Date format (maintaining the same DD/MM/YY format)
for storing in my Oracle DB.. ??
Use a SimpleDateFormat:
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy");
String stringWithDate = "16/07/13";
Date theDate = sdf.parse(stringWithDate);
//store theDate variable in your database...
Note that SimpleDateFormat#parse throws ParseException.
UPDATE: Using Java 8 and LocalDate
LocalDate localDate = LocalDate.from(
DateTimeFormatter.ofPattern("dd/MM/yy")
.parse(fecha));
If you need to pass this to java.sql time objects, you can see this answer on How to get a java.time object from a java.sql.Timestamp without a JDBC 4.2 driver?
I don't know Java and I'm not super familiar with Oracle, but this may help.
In MS SQL Server I've seen all kinds of bad stuff happen when people try to post stuff using specific date formats. Windows date settings can vary so problems are almost guaranteed. From that point of view your
(maintaining the same DD/MM/YY format)
rings alarm bells
I'm yet to have issues as I usually fall back on handling dates in a "standardised" way.
'yyyymmdd'
select CAST('19900506' AS DATETIME)
is very predictable, so if you want predictable you need the oracle equivalent
it also works for date + time
'yyyymmdd hh:mi:ss.mmm'
select CAST('19900506 01:01:01.000' AS DATETIME)
Oracle/PLSQL will have similar functions that work in an controllable way. Use these functions to save values correctly then your data can be reliably output in whatever format you specify at the time of retrieval

Save date in database in this format dd/MM/yy

Is it possible to save date values in the database of this format dd/MM/yy in Grails? I know I can customized the format in the views but I need the values to be returned as json and also return the values of dates in json in that format. Any suggestion will be appreciated.
Try this on your presentation layer, don't save time in that format in database. use following code to format the time according to your need.
Date date = new Date( );
SimpleDateFormat simpleFormat = new SimpleDateFormat ("dd/MM/yy");
System.out.println("Date: " + simpleFormat .format(date));
But if you want to save the data in this format in databse, then remember it returns a string and you will have to save the date in String format in database. Which I wouldn't recommend because of many reason.
You should not store the date as a formatted string because you lose the ability to do many things with that field, such as sort it or compare it. Always use the database's native date format for storage. If you want to change the format there are many places to do it, including the presentation layer (as others have suggested) and the database query layer. Format the date in the query if you want to do minimal processing in Java/Javascript.
Agreed with others you should not save in the database in String format. To format a Date using Groovy you can use the String.format() method.
​String.format('%tY-%<tm-%<td', new Date())​
See the Groovy dates documentation for further examples.

Sql timestamp to Java date?

I have a database which is going to have UMT timestamps in standard sql format. How can I pull that data and set a java date object with it?
As far as I know mysql is yyyy-mm-dd hh:mm:ss As for java, the date / time stuff has always eluded me.
If anyone knows of a good library for this I am open to suggestions.
Why don't directly read it as Date
Date date = resultSet.getTimestamp("date_field");
Timestamp timestamp = resultSet.getTimestamp("date_time_field");
See
ResultSet.getTimeStamp()
A Timestamp is a subclass of a Date, which means it is usable everywhere where a Date is. The only difference is, Timestamp is more precise (due to the SQL specification) than Date is.
Just use:
Timestamp t = resultSet.getTimestamp("columnname");
Date d = t;
That having said, there are some benefits of converting the JDBC returned timestamp into a proper Date value, omitting nanoseconds. When you compare a Timestamp and a Date in some remote part of your app, the Timestamp and the Date won't be equal, even though they seem to be "rougly" the same time value. So if this could cause problem, create a new Date instance using only the .getTime() value returned by Timestamp)
More on this in my blog: Timestamp and Date equality when using Hibernate
(even though the blog entry is about Hibernate, it applies to your case as well)

store date in database

I have a JSP page in which I am entering a date in a textbox and retrieving the value from the textbox and the value is stored in a string variable. I want to convert this value to date and that value will be stored in database. I use MySQL.
Use SimpleDateFormat.parse() to parse your date string into a Date object and store that or the getTime() of that in the database.
Here's an example of parsing the date:
String pattern = "MM/dd/yyyy";
SimpleDateFormat format = new SimpleDateFormat(pattern);
Date date = format.parse("03/24/2011");
See this answer about storing dates in MySQL.
You will need to convert your date String into a java.sql.Date object, like so
java.sql.Date date = java.sql.Date.valueOf("2011-01-12"); //where date is of pattern "yyyy-MM-dd"
Once date is created, use the PreparedStatement.setDate(int index, java.sql.Date date) to store the date in the database.
If - for now - you do not need the actual Date in your program you can just call setString on the appropriate field in the prepared statement to have the database parse the date.
I would always store a value that does not depend on a timezone in a database; Date.getTime() does nicely and can always be converted to something you can display or work with otherwise, and it avoids lots of troubles when it comes to daylight saving time.

Categories

Resources