Setting timestamp to Calendar in java - java

I am using following code to set SQL timestamp in calendar instance, it is working fine. Is this correct?
TimeStamp expireDate= ab.getUExpireDate();
Calendar cal = Calendar.getInstance();
cal.setTime(expireDate); // ← this line

You can check the difference in util.Date and sql.Date in the following post
java.util.Date vs java.sql.Date

You can import:
1)java.sql.Timestamp
***The biggest difference between java.sql.Date and java.sql.Timestamp is that the java.sql.Date only keeps the date, not the time, of the date it represents. So, for instance, if you create a java.sql.Date using the date and time 2014-12-24 21:20, then the time (21:20) would be cut off. If you use a java.sql.Timestamp then the time is kept.
method to add timeStamp object in Calender is :
2) cal.setTime(expireDate);

Related

java code to convert UTC time to local datetime with an offset compare

We receive datetime elements relative to the UTC time like 2004-04-12T13:20:00Z.
And we would like to output the datetime in the local datetime, that is expressed with an offset relative to the UTC time like 2004-04-12T12:20:00-01:00.
With the Java 8 date and time classes this is straightforward. Only catch is, we need to go through ZoneDateTime if we want to pick om the computer’s default time zone, and then on to OffsetDateTime to get the output format you requested (another option would be formatting the date and time using a specific DateTimeFormatter; now I am relying on OffsetDateTime.toString()).
String utcTime = "2004-04-12T13:20:00Z";
OffsetDateTime dateTimeWithOffset = Instant.parse(utcTime).atZone(ZoneId.systemDefault()).toOffsetDateTime();
System.out.println(dateTimeWithOffset);
On my computer the above prints
2004-04-12T14:20+01:00
In the answer and the code I have on purpose avoided the term “local date-time” that you used in the question. This is to avoid confusion with the class LocalDateTime, which is used for a date and time without any time zone or offset information.
Use ZonedDateTime from the java 8 API.
ZonedDateTime.ofInstant(Instant.parse("2004-04-12T13:20:00Z"), ZoneId.of("CET"))
it will give you 2004-04-12T15:20+02:00[CET]
Hope the below solution works.
String date_s = "2004-04-12T13:20:00Z";
SimpleDateFormat dt = new SimpleDateFormat("yyyyy-MM-dd'T'HH:mm:ss'Z'");
Date date = dt.parse(date_s);
Calendar cal = Calendar.getInstance(); // creates calendar
cal.setTime(date); // sets calendar time/date
cal.add(Calendar.HOUR, 1); // adds one hour (do any offset that you want here)
String out = dt.format(cal.getTime());
System.out.println(out.substring(1));
Using the Java 8 JDK, you can use the java.time.Instant class to refer to UTC time. and the folloowing classes for the offset times :
java.time.LocalDate
java.time.LocalTime
java.time.LocalDateTime
Example :
Instant instant = Instant.now();
LocalDateTime dateTime = LocalDateTime.ofInstant(instant, ZoneId.ofOffset("MyZoneId", ZoneOffset.ofHours(3)));

How to convert date-time "yyyy/MM/dd HH:mm:ss" that's stored in a String to a Date object?

I want to insert into a Mysql column (DATETIME column) a time & date . For that purpose i use
the DATETIME field .
But on the JAVA side , I need to have a Date object with the time & date .
Consider the code :
Calendar cal = Calendar.getInstance();
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
String str = dateFormat.format(cal.getTime());
System.out.println(str);
This code produces :
2014/03/19 01:11:35
How can I convert it to a Date object in the format yyyy/MM/dd HH:mm:ss , so it would be
possible to put it in the mysql column of DATETIME ?
Much appreciated
The getTime() method of Calendar returns a Date object.
For JDBC, you'll use a java.sql.Timestamp to preserve the time component. (I think a java.sql.Date loses the time component.)
For example:
preparedStatement.setTimestamp(new java.sql.Timestamp(cal.getTime()));
First point: Date objects have no "format" - they just represent an instant in time.
If you print them, you get the default toString() implementation for Date.
Second point: You don't need to format a Date to use it with JDBC.
You should use a prepared statement, then call setObject(), to set the parameter value - the JDBC driver will do the rest, including wrapping in quotes if that's required for the data type.
Final point: Never use Calendar unless you have to.
In this case, simply new Date() will do the job.

Error - java.sql.Timestamp cannot be cast to java.sql.Date in JFreeChart

While i'm retrieving data from my database to add to a chart using JFreeChart I get the error:
java.sql.Timestamp cannot be cast to java.sql.Date
I have four columns the first three are retrieved properly using a case but while going through the final column it goes to the correct case:
case Types.TIMESTAMP: {
But then the error occurs on this part:
Date date = (Date) resultSet.getObject(column);
The data within the database is formatted like this (HH,MM,SS).
Edit -
Also would like to add this class is included with the JFreeCharts API - JDBCCategoryDataset.java
Date date = new Date(((Timestamp)resultSet.getObject(column)).getTime());
Firstly, dont use a java.sql.Date for time - It will not yeild the result you want... unless you want your time to be set to 0 for the current timezone
From Docs:
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.
Also why use ResultSet.getObject and cast when you could just use ResultSet.getDate() or ResultSet.getTime() or ResultSet.getTimestamp() where you want to use either of the seocnd two.
Then if you must use a date object, make a java.util.Date like so
java.util.Date yourDate = new java.util.Date(resultSet.getTimestamp("Column").getTime());
Or if it is in the database as the String "(HH,MM,SS)" then you might want to get a string and use a formatter like a SimpleDateFormat
SimpleDateFormat sdf = new SimpleDateFormat("(hh,MM,ss)");
Date aDate = sdf.parse(resultSet.getString("column");

Convert java.sql.Timestamp to local timezone

I am retrieving results from a timestamp mysql database column. I need to convert these results to my local timezone.Timestamp timestamp = rs.getTimestamp("mytimestamp");
I think this might work:
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(timestamp.getTime());
I believe they are both based on epoch.
java.sql.Timestamp just like java.util.Date which it extends holds time since since January 1, 1970, 00:00:00 GMT with the only difference that it also holds nanos (see API). It does not depend on time zone and you cannot convert it to local time zone.
java.sql.Timestampobjects don't have time zones - they are just like java.util.Date.
However you can display time in your TimeZone like
Calendar localTime = Calendar.getInstance(TimeZone.getDefault());
localTime .setTimeInMillis(timeStamp.getTime());

Java/Servlet: get current sql.Date

What I need to do is:
1) Get user's locale from request.
2) Create new sql.Date object with current date and time, based on user's locale
3) Write it in MySQL db, column type: TIMESTAMP
What I got is:
java.util.Locale locale = request.getLocale();
java.text.DateFormat dateFormat =
java.text.DateFormat.getDateTimeInstance(
java.text.DateFormat.LONG, java.text.DateFormat.LONG, locale );
java.util.Date date = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date( date.getTime() );
Date is OK, but have a problem with time - always 12:00:00 AM.
Any suggestions? Is there a more efficient way to do this?
Even a more compact solution ;)
java.sql.Date timeNow = new Date(Calendar.getInstance().getTimeInMillis());
There is one more simple solution for it.
use this code to get current date using java.util.Date
java.util.Calendar cal = java.util.Calendar.getInstance();
java.util.Date utilDate = cal.getTime();
java.sql.Date sqlDate = new Date(utilDate.getTime());
If you want the time, you need a java.sql.Timestamp not a java.sql.Date, and a timestamp column in the database.
Note that request.getLocale uses the value of Accept-Language heading and may not always give you the correct locale.
Getting the time zone based on the locale may not be their actual time zone .
An example: Here in Australia, the locale is 'en-AU', but we have a few time zones with up to 3 hours difference.
I'd guess in the US they have this problem too.
A possible solution is to store UTC time instead. If the user then adjusts his timezone in, say, his prefrences, or you use some other method of passing the time zone (client/browser info say via AJAX) then you can adjust the UTC time based on that using a java.util.Calendar instance.

Categories

Resources