I have a DateTime field in my SQL database holding and when I try to show it in my JSP page and format it using "dd-MM-yyyy hh:mm:ss", it displays correctly only the date part. For example, for the date "2012-01-19 12:13:48" stored in the database it shows "19-01-2012 12:00:00". What may be the problem?
Code:
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
sdf.format(rs.getDate("comment_date")); //rs -> ResultSet
From the javadoc for java.sql.Date:
To conform with the definition of SQL DATE, the millisecond values wrapped by a java.sql.Date instance must be 'normalized' by setting the hours, minutes, seconds, and milliseconds to zero in the particular time zone with which the instance is associated.
In order to preserve time information as well, you should be using java.sql.Timestamp. In other words, change rs.getDate() to rs.getTimestamp().
An interesting date/time library you could have a look at is Joda Time. It solves many issues of the date/time implementations in the standard library.
Related
From my database i retrieve value as :
20-DEC-17 10.15.53.000000000 AM
I want above java.sql.Timestamp to be converted to Instant time as :
2017-12-20T10:15:53Z
I tried following with current time stamp
Timestamp ts2 = new Timestamp(date1.getTime());
Date tradeDate1=new Date(ts2.getTime());
Instant tradeInstant = tradeDate1.toInstant();
System.out.println("Tade Instant"+ tradeInstant);
Actual time stamp: Fri Jun 22 16:07:35 IST 2018
What is prints in instan : Tade Instant2018-06-22T10:37:35.420Z
The hours/mins/seconds are updated which I dont want - is there a way this can be retained as is?
I am assuming that you are using at least Java 8 and at least JDBC 4.2. I am further assuming that the timestamp doesn’t have time zone or offset information in the database, but is to be understood as a timestamp in UTC (which is a recommended practice). In this case I would consider it safest to add the information about UTC offset explicitly in Java:
PreparedStatement yourPreparedStatement
= yourConnection.prepareStatement("select trade_timestamp from your_table");
ResultSet rs = yourPreparedStatement.executeQuery();
while (rs.next()) {
LocalDateTime tradeDateTime = rs.getObject(1, LocalDateTime.class);
Instant tradeInstant = tradeDateTime.atOffset(ZoneOffset.UTC).toInstant();
System.out.println("Trade Instant: " + tradeInstant);
}
Note that the code avoids the outdated Timestamp class completely. A LocalDateTime is a date and time of day without time zone or offset. If your database datatype had been timestamp with time zone, you could have passed either Instant.class or OffsetDateTime.class to rs.getObject and have got an Instant or an OffsetDateTime back. JDBC 4.2 only specifies support for OffsetDateTime, but many drivers support Instant too. Obviously with Instant you need no further conversion. With OffsetDateTime do
Instant tradeInstant = tradeDateTime.toInstant();
Depending on your database and its capabilities it is also possible that you can set UTC as offset/time zone on the database session so you can get the correct instant even from timestamp without time zone.
Discussion: Arvind Kumar Avinash in a comment recommends that one should rely only on the types officially supported by JDBC 4.2, that is, LocalDateTime and OffsetDateTime for our purposes. The types are mentioned at the bottom of the article Why do we need a new date and time library? on Oracle’s web site, there’s a link at the bottom. Arvind Kumar Avinash further refers us to PSQLException: Can't infer the SQL type to use for an instance of java.time.Instant, also linked to at the bottom. Since comments are fragile, I wanted to include the essence here in the answer.
What went wrong in your code?
It seems your database session understood the timestamp as a date and time in your local time zone (IST, I assume it’s for India Standard Time (other interpretations exist)). According to Mark Rotteveel’s informative comment this behaviour is required by JDBC, but it doesn’t agree with your need when the value is in UTC. Therefore it gave you the wrong point in time, though it looked right when you printed it. The conversion in itself was correct.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Why do we need a new date and time library?
PSQLException: Can't infer the SQL type to use for an instance of java.time.Instant. on doobie’s GitHub page (doobie is a JDBC layer for Scala)
Building from the comment about not using SimpleDateFormat, I have moved to DateTimeFormatter:
Date today = new Date();
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss") // same format
.withLocale(Locale.UK) // UK locale
.withZone(ZoneId.systemDefault());
String output = dateTimeFormatter.format( today.toInstant() );
System.out.println( output );
Running gives you:
2018-06-22T14:14:26
I have created a SimpleDateFormat, which only prints "up to seconds":
/* simple date format */
DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
/* get toInstant() and convert to date */
Date myDate = Date.from(today.toInstant());
/* myDate formatted using DATE_FORMAT */
String formattedDate = DATE_FORMAT.format(myDate);
System.out.println(formattedDate);
I tried to remove minute from given time, but some how it is converting time to my local time zone
String timeStamp="20180623 05:58:15" ;
dateFormat inputFormatter = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
Date date = inputFormatter.parse(timeStamp);
date.setMinutes(-2);
logger.info("Before converting : "+date);
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
Here it is converting to my local time and subtracting 2 minutes from given time, but I don`t want to check the time zone here instead, what ever time I give it should just subtract 2 minutes.
Start with understanding into how Date works. When you do...
logger.info("Before converting : "+date);
The Date class uses it's toString method to format the the date/time information represented by the Date class into a human readable format. It doesn't "convert" the date/time value in anyway
So taking your code from above (and reworking it so it works), it outputs...
Before converting : Sat Jun 23 04:58:15 AEST 2018
20180623 04:58:15
on my machine - why are the values the same? Because the input doesn't have any time zone information, so the time is likely been treated as been in the machines local timezone (and the value is simply been formatted for output).
Date is just a container for the number of milliseconds since the Unix Epoch, it's format agnostic - meaning it carries not formatting information.
Date is also effectively deprecated - not to mention that setDate is also very much deprecated
A better (starting point) overall is to make use the newer date/time API introduced in Java 8 (and which has back port support for earlier versions of the API)
String timeStamp = "20180623 05:58:15";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss", Locale.ENGLISH);
LocalDateTime ldt = LocalDateTime.parse(timeStamp, formatter);
ldt = ldt.minusMinutes(2);
System.out.println(ldt);
System.out.println(ldt.format(formatter));
This will output...
2018-06-23T05:56:15
20180623 05:56:15
The input and the output are still consider as been in the machines local time zone.
but I don`t want to check the time zone here instead, what ever time I give it should just subtract 2 minutes
Just remember, the API still needs to have some concept of time zone, weather it's the local time zone or UTC/GMT, but since your input doesn't provide any kind of information, you need to make a choice over "how" best to handle that issue. The example above just "assumes" local time, but you could use ZonedDateTime and convert it to "common" time zone from which your operations are executed or, better yet, make all your strings carry time zone information
Oh, and for the love of my sanity, stop managing date/time values in String format - get them into an appropriate container as soon as possible and manage them from there - I've spent a week wrangling inappropriately formatted date strings and I'm not happy Jan, not happy
I am using JPA and MySQl
In my domain object i have a date field as
#Temporal(TemporalType.TIMESTAMP)
private Date lastSeenDate;
From my UI the date goes as a String in format dd-mm-yyyy
I used
final DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
final Date date = format.parse(dateString);
but for String date
06-06-2013
the date stored in mysql is
0011-12-04 00:00:00.0
How do I store it into mysql to match the mysql format
The class Date represents a specific instant in time, with millisecond
precision.
From: http://docs.oracle.com/javase/6/docs/api/java/util/Date.html
The date class always has a time component.
All dates in Java are essentially timestamps as they represent a single millisecond in time.
There's no way I can think of to deal only with dates but you might want to have a look at java.util.Calendar. If you can set the hours, minutes, seconds and milliseconds all to zero (or other defined time) you can then work with days, months and years more naturally. It's not a very good offering but it works well enough.
According to JavaDocs: java.util.Date allocates a Date object and initializes it so that it represents the time at which it was allocated, measured to the nearest millisecond.
So, it works like a database Timestamp. It would always have a time component although it may be all zeroes that is representing a midnight. But, you could use the same SimpleDateFormat to print out the java.util.Date without its time component.
final DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
final Date utilDate = sdf.parse("2013-06-20");
System.out.println(sdf.format(utilDate)); // prints back 2013-06-20
Or, you may want to look into java.sql.Date which does not have a time component.
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
I have timestamp string: "1989-01-01 00:00:00" and i need convert it to local date format.
I execute:
SimpleDateFormat TIMESTAMPFORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
DateFormat.getDateFormat(getContext()).format(TIMESTAMPFORMAT.parse("1989-01-01 00:00:00"));
And getDateFormat returns 31.12.1988
Why?
How can I receive 01.01.1989???
In order to skip time-zone when formatting, I would suggest you to set it to default as below:
SimpleDateFormat TIMESTAMPFORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
TIMESTAMPFORMAT.setTimeZone(TimeZone.getTimeZone("GMT"));
This is probably to do with the time zones involved. I strongly suspect that you're formatting in a different time zone to the one you're using for parsing, and the value goes to before midnight, basically. If you can use the same time zone on both, it's likely to work.
If you possibly can, I'd encourage you to use Joda Time instead though - you really want a LocalDate.
I'd like to insert the value derived from this JXDatePicker into a Date field in Java DB. How should I get ONLY date off this controller in a way that time is represented as dd/mm/yyyy and nothing else??!
You can get the Date from the JXDatePicker.getDate() and then use a SimpleDateFormat to format the date into the required format.
Try:
SimpleDateFormat formater = new SimpleDateFormat("dd/MM/yyyy");
formater.format(myDatePicker.getDate());
Notice that instead of the mm that you've used I used MM to represent the month. Please see the SimpleDateFormat javadoc for pattern letters you can use.
Follow-Up
I feel compelled to mention, for completeness, that it is generally a bad idea to put formatted strings representing dates into a database; what happens when you want to display it in another format, for instance, or do a simple comparison using SQL.
One way to store date/times is to use the timestamp that you get from Date.getTime(). Here's the Date class' getTime() javadoc:
Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT
represented by this Date object.
Storing this representation of a Date in your database makes it much simpler to create a Date object when you retrieve the timestamp:
Long myTimeStamp = getTimeStampFromResultSet();
Date date = new Date(myTimeStamp);
Or use the column in SQL to do a simple comparison:
SELECT * FROM MY_TABLE WHERE MY_DATE > ?
It also makes it somewhat portable so you can, for instance, send the timestamp to a thin client that is built using a different technology.
That being said, it is also in your best interest to use a date and time library like Joda Time instead of using the unreliable and inconvenient Java Date or Calendar classes.