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)
Related
I have a Timestamp object and a TimeZone object
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
TimeZone userTimeZone = preferenceService.getPreferredTimezone();
I want a function which modifies timestamp as per the userTimeZone . The function should return Timestamp. Could someone help ?
Your question is non-sensical. A Timestamp instance represent an instant in time. It doesn't have timezone info and isn't a timezoned stamp.
Instead, when showing a Timestamp to a user, in the step of 'convert this computer-time-kept concept to something to show the user', you'd do the job there. You wouldn't do that by first 'converting the timestamp to this timezone', you'd either do that in one go, or better yet, get to the java.time package as fast as possible because all other time libraries (including those in almost all DB engines) are non-sensical.
In java.time terms, you'd get to a ZonedDateTime, and hten you can convert that to another zone, and from there, potentially via a LocalDateTime, to rendering it to the user.
Given that you said the function must return a Timestamp, the code that uses this method is broken, so fix it there.
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
I am pulling data from an external source into my program and it has an ISO8601 Date attached to it but one of our requirements is that the hour/minutes/seconds get set to zero. This happens before I receive the date. So I get this from the data.
2013-05-17T00:00:00.000Z
for instance. I am then putting that value into a Joda DateTime object called "businessDay". I do some processing based off of this value but then I need to persist it to MongoDB.
Since a Joda DateTime object is not serializable I need to put the DateTime object into a Date object and persist it to Mongo (and reverse that when it comes out).
When I use Joda in this way
businessDay.toDate() -- I receive a Java Date object but it is
Sun May 19 20:00:00 EDT 2013
and businessDay printed out normally is
2013-05-20T00:00:00.000Z
It converts it to my local time zone, which is then making it the previous day.
What I want is to convert the DateTime object into a Date object that retains the values.
I've been trying a bunch of things with DateTimeFormatter but I can't get it to work at all. I've also been deleting all of my efforts otherwise I would paste them here but I've been doing this all day to try to figure this out.
Thank you for any assistance.
EDIT:
Showing method that converts a String Date into a Joda DateTime object.
private DateTime asDateTime(String value) {
// Was experiencing an issue converting DateTime to date, it would convert to localtime zone
// giving me the wrong date. I am splitting the value into its year/month/day values and using a dateFormatter
// to give me an appropriate format for the date. Timezone is based on UTC.
String[] splitValue = value.split("-");
String[] splitDay = splitValue[2].split("T");
int year = Integer.parseInt(splitValue[0]);
int month = Integer.parseInt(splitValue[1]);
int day = Integer.parseInt(splitDay[0]);
DateTime date = new DateTime(DateTimeZone.UTC).withDate(year, month, day).withTime(0, 0, 0, 0);
return date;
}
Firstly, if you've just got a date, I would suggest using LocalDate rather than DateTime. However, I think you've misunderstood what java.util.Date does:
It converts it to my local time zone, which is then making it the previous day.
No, it really doesn't. Your DateTime value is precisely 2013-05-20T00:00:00.000Z. Now a java.util.Date is just a number of milliseconds since the Unix epoch. It doesn't have the concept of a time zone at all. It's equivalent to a Joda Time Instant.
When you call toString() on a Date, that converts the instant in time into your local time zone - but that's not part of the state of the object.
So both your DateTime and your Date represent midnight on May 20th UTC. I don't know what MongoDB is then doing with the value, but just the conversion from Joda Time to java.util.Date has not performed any time zone conversion for you.
My apologies, I found out that it wasn't an issue of the Dates it was a completely different issue. MongoDB can accept a Java Date and will convert it to UTC format automatically.
My fault for creating this post before looking at this problem from different angles.
Do I accept the other answer and give the bounty? Just curious if that is the correct thing to do on Stack Overflow.
So far, I have not found a clear answer to this.
I'd like to know what the equivalent is for a SQL type DATETIME and the java type, using a PreparedStatement.
I have found: http://www.java2s.com/Code/Java/Database-SQL-JDBC/StandardSQLDataTypeswithTheirJavaEquivalents.htm
But it states that SQL type "DATETIME" is the same as sql.date, but when looking at the SQL date docs (http://download.oracle.com/javase/7/docs/api/java/sql/Date.html), it says the time is truncated (all zeros).
What I want is to be able to specify a preparedStatement.setDateTime() or some sort.
The only other way I see is using a timestamp, but that would require me to change the column type, while I cannot imagine someone else never had this problem before?
Any hints?
Edit: I am using MYSQL.
The java.sql package has three date/time types:
java.sql.Date - A date only (no time part)
java.sql.Time - A time only (no date part)
java.sql.Timestamp - Both date and time
You want the last one: java.sql.Timestamp.
If you are using these types, you don't need to call a specific setter; just use:
java.util.Date date = new Date();
Object param = new java.sql.Timestamp(date.getTime());
// The JDBC driver knows what to do with a java.sql type:
preparedStatement.setObject(param);
The equivalent of MS SQL Server or MySQL DATETIME data type or Oracle DATE data type is java.sql.Timestamp.
In Java we have java.util.Date to handle both Date and Time values.
In SQL, you have commonly Dates (only dates), Time (only time) and DateTime/Timestamp (date and time).
In your Java program, usually you'll always have java.util.Date, so each time you're setting Dates/Times/DateTimes in PreparedStatements, always choose exactly which one you need, according to the database.
I had a similar problem with my Mysql having SQL date and locally in my app i only had Date
I solved like this
java.sql.Date dataStartSql = new java.sql.Date(start.getTime());
After that used the setDate normally, and I used a getTimestamp to retrive the first value.
where start is a Date object.
How can I convert time in unix timestamp to normal time?
Your question is vague and ambiguous. I'll leave the timezone ambiguity away.
How can I convert time in unix timestamp to normal time?
I suspect that you're somehow obtaining a long or maybe a String value from the DB instead of a Date. In JDBC, you would normally like to use the appropriate methods to obtain the DB-specific datatypes. The MySQL TIMESTAMP datatype can be obtained by ResultSet#getTimestamp() which gives you a java.sql.Timestamp which in turn is a subclass of java.util.Date.
In a nut, the following should do:
Date date = resultSet.getTimestamp("columnname");
To format it further in a human readable format whenever you're going to present it to the enduser, use SimpleDateFormat. Click the link, it contains an overview of all patterns. Here's an example:
String dateString = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
To do all the other way round, use respectively SimpleDateFormat#parse() and PreparedStatement#setTimestamp().
Unix timestamp is seconds since "epoch". Java's currentTimeMillis are milliseconds since "epoch". You can get a Java Date object with a simple multiplication like this:
Date dateFromUnixTime = new Date( 1000l * unixTime) ;
From there, you can format it using the normal date formatting tools in Java.