Removing seconds from a sql Time in java - java

I am taking data from a sql database and then displaying this data in the form of graphs. A graph I am making bases the data off of the time. I want to get rid of the seconds because it is useless for my application and takes up room.
I tried using a calender object to remove the seconds from it like this:
ArrayList<Time> ints3 = new ArrayList<Time>();
while ( rs.next() ){
ints3.add(rs.getTime(ints.get(0)));
}
Calendar instance = Calendar.getInstance();
instance.setTime(ints3.get(1));
instance.clear(Calendar.SECOND);
ints3.set(1, (Time) instance.getTime());
This did not work however because you can not cast a java.util date into a sql time. How can I go about removing the seconds part of the time.

The answer to your need (which is to symbolize the Date without displaying the seconds) is to use the DateFormat class. Given that Time is a java.sql.Time object, convert it to a Date first:
Date myDate=new Date(Time.getTime());
DateFormat df=new SimpleDateFormat("H:mm");
String myDateStr=df.format(myDate);

I'd like to comment this but I do not have enough reputation points. I believe this answer could help you
https://stackoverflow.com/a/21250071/2987444
You could use Jodatimes, methods to add/take away seconds and then convert back

This did not work however because you can not cast a java.util date into a sql time That's strange because java.sql.Time extends java.util.Date.
You're downcasting the result of Calendar#getTime but this won't work. Instead, create an instance of java.sql.Time and pass as parameter the time in millis:
//ints3.set(1, (Time) instance.getTime())
ints3.set(1, new Time(instance.getTime().getTime()));
Still, it will be way better to change ArrayList<Time> to List<Date> (java.util.Date).

Well you can use setTime method in Time class which accepts a long value that you can get by calling getTimeInMillis() of Calendar class(in your case after clearing seconds part).But even if you do that the Time object will take Hour,minute and the seconds part(with seconds part set to zero).If you don't want seconds part in the display then you can use concatenation of getHours and getMinutes methods of Time class.

Related

Time.valueOf method returning wrong value

I used the method Time.valueOf to convert the String "09:00:00" into Time object as follows: Time.valueOf (LocalTime.parse("09:00:00")).
When I call getTime () to display the value I get: 28800000 ms instead of 32400000‬‬ ms (calculated from calculator).
Did I make an error when I used Time.value Of ? Because I don't understand why I get the wrong value.
Thanks.
That's caused by time zone issues. If you do
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
Before your code you will get 32400000‬‬ as you expect.
Time.valueOf (LocalTime.parse("09:00:00")) assumes the nine is at your local time zone so it converts it to UTC.
For example if the time zone is "Asia/Jerusalem" (you can simulate it with TimeZone.setDefault(TimeZone.getTimeZone("Asia/Jerusalem")); which was UTC+2 at 1 January 1970 it will convert 9 o'clock to 7 o'clock. You can see it with System.out.println(time.toGMTString());
As always in questions about the old java time api I have to give you an obligatory recommendation to always use only the modern post java8 api.
Stick to java.time.LocalTime
I recommend you stick to LocalTime from java.time, the modern Java date and time API, and don’t use java.sql.Time. The latter class is poorly designed, a true hack, indeed, on top of the already poorly designed java.util.Date class. Fortunately it’s also long outdated. There was a time when we needed a Time object for storing a time of day into a database column of datatype time or transferring a time to an SQL query using that datatype. Since JDBC 4.2 this is no longer the case. Now your JDBC driver accepts a LocalTime object and passes its time value on to the database.
So if you’ve got a string, parse it into a LocalTime object the way you already did:
LocalTime time = LocalTime.parse("09:00:00");
If you don’t need to go through a string, you may obtain the same result using the of factory method, for example:
LocalTime time = LocalTime.of(9, 0);
I don’t know why you should want to convert it to milliseconds, but you can:
int milliOfDay = time.get(ChronoField.MILLI_OF_DAY);
System.out.println(milliOfDay);
Output is:
32400000
This is the value you said you expected.
To insert the LocalTime into your database:
PreparedStatement ps = yourDatabaseConnection.prepareStatement(
"insert into your_table(your_time_col) values (?)");
ps.setObject(1, time);
int rowsInserted = ps.executeUpdate();
Note the use of setObject(), not setTime().
If you do need a Time object for some legacy API that you don’t want to upgrade just now, the conversion you made is correct.
Your expectations were wrong, your conversion was correct
Did I make an error when I used Time.value Of ? Because I don't
understand why I get the wrong value.
No, the other way around. You made no error. And in this case you got the correct value. It’s the poor and confusing design of Time playing a trick on you (I said you shouldn’t want to use that class). I am not sure it’s documented, but Time.valueOf (LocalTime.parse("09:00:00")) gives you a Time object that internally holds a point in time of Jan 1, 1970 09:00 in the time zone of your JVM. From the millisecond value you got, 28 800 000, it seems that this time is equal to 08:00 UTC. Was your time zone at UTC offset +01:00 in the winter of 1970? The getTime() method returns the number of milliseconds since Jan 1, 1970 00:00 UTC.

How can I retrieve the difference between two Date instances in minutes?

According to the Talend docs, it is possible to calculate the difference between two dates using TalendDate.dateDiffFloor up to seconds and milliseconds.
However, the docs don't say how (or which format parameter has to be specified).
I have to get this value in seconds as it will feed into a tInfiniteLoop component.
I have tried with "mmmm" and "mm" with no luck. In that case I get the error:
Exception in component tMap_3
java.lang.RuntimeException: Can't support the dateType: mm ,please try "yyyy" or "MM"
at routines.TalendDate.diffDateFloor(TalendDate.java:661)
at timeouttester.job_2_0_1.job_2.tInfiniteLoop_2Process(job_2.java:1156)
at timeouttester.job_2_0_1.job_2.runJobInTOS(job_2.java:1616)
at timeouttester.job_2_0_1.job_2.main(job_2.java:1464)
Which argument do I have to specify to get minutes? And, if not doable, maybe there is a workaround doing this in "vanilla" Java if not possible via Talend?
I am currently using the following statement in a tMap component:
TalendDate.diffDateFloor(TalendDate.parseDateInUTC("EEE, d MMM yyyy HH:mm:ss", Var.expires), TalendDate.getCurrentDate(), "mmmm")
I have no clue about Talend but as you said vanilla is also possible for you: You may use the class Duration which represents the duration between two objects of type Temporal. Such a temporal class would, for example, be Instant which is a snapshot on the time line. Instant has great support in the API. You can retrieve one from Date#toInstant, or from Calendar#toInstant and more.
See this small example:
Date dateBefore = new GregorianCalendar(2014, Calendar.FEBRUARY, 11).getTime();
Instant before = dateBefore.toInstant();
Instant now = Instant.now();
Duration duration = Duration.between(before, now);
System.out.println("Days: " + duration.toDays());
However, If I'm not mistaken the class Instant itself is only precise down to milliseconds. If that is not enough, you may use another class which implements Temporal or create your own.
For your application, you are probably interested in:
Duration#toMinutes()
Duration#toMillis()
Note that the returned value (long) of those methods are rounded downwards (floor). So if the real amount of minutes where something like 1.453, toMinutes() will return 1 and toMillis() returns 1453.

From jFreeChart Millisecond to java.util.Date

Regarding jFreeChart's Millisecond,
How can I get a java.util.Date object from a Millisecond instance?
From the docs, it only seems possible to subtract the milliseconds within Millisecond.
Since a Millisecond object is constructed like so:
Millisecond ms = new Millisecond(
millisec,
second,
minute,
hour,
day,
month,
year);
I should be able to extract a valid Date object as well.
Edit
I need a Date object that gives back the exact time up to the millisecond accurate.
Does .getStart() provide this?
[ANSWER]: YES
Millisecond is like any other RegularTimePeriod in JFreeChart, so you can just
Date d = ms.getStart();
or
Date d = ms.getEnd();
depending on whether you want a date referring to the beginning or the end of your millisecond (same value either way).
See The JFreeChart API for more info.
EDIT: Adding code here since comments kill formatting:
Millisecond ms = new Millisecond();
System.out.println(ms.getStart().getTime());
System.out.println(ms.getEnd().getTime());
will print the same millisecond twice.
As far as I can see the Millisecond Class represents the time period of a millisecond and I'd assume the the getStart and getEnd Methods inherited from RegularTimePeriod return (nearly) the same Date of which one is one you're looking for.
(my answer was late) Perhaps you could use this code:
java.util.Date date = new java.util.Date(freeMillis.getMillisecond());
edit: scrap that, freeMillis.getMillisecond() returns just a millisecond part.

How to store and retrieve milliseconds in a date object in Java?

I'm making a basic Java program that reads in a subtitle (.srt) file and I would like to store each time as a Date object. I really only need to keep track of Hours, minutes, seconds, and milliseconds (to 3 digits). I think I am able to store it using this:
String start = "00:01:01,604";
DateFormat sdf = new SimpleDateFormat("hh:mm:ss,SSS");
Date startDate = sdf.parse(start);
For retrieving, I can do something like this:
return String.format("\nStart: %d:%d:%dText: %s\n", startDate.getHours(),startDate.getMinutes(), startDate.getSeconds(), text);
I'm looking for something that would do something similar to getMilliseconds (if it existed). Thank you very much!
What you're handling is not a date! Don't use the Date class to handle it! Dates have strange extra rules that you don't care about and that could easily trip you up (just think of leap years, leap seconds and time zones).
You should either
use a long to hold the milliseconds and handle the calculation on your own (it's not so hard, you're not implementing a calendar) or
use an existing duration class such as the one from Joda Time.
The recommended way to get access to part of date (hours,minutes, etc.) in Java is now using Calendar.get(Calendar.MILISECONDS), see javadocs. In case of your code it would look like this:
Date startDate = sdf.parse(start);
Calendar calendar = Calendar.getInstance();
calendar.setTime(startDate);
int milliseconds = calendar.get(Calendar.MILISECONDS);
P.S. Please note that regarding to javadocs Date.getHours(),Date.getSeconds(), etc. methods are currently deprecated anyway. Don't use them :).
Just call date.getTime() and get milliseconds.
You can always use Date.getTime() for getting value in milliseconds. It will return a value in long format

How do I combine a java.util.Date object with a java.sql.Time object?

I'm pulling back a Date and a Time from a database. They are stored in separate fields, but I would like to combine them into a java.util.Date object that reflects the date/time appropriately.
Here is my original approach, but it is flawed. I always end up with a Date/Time that is 6 hours off what it should be. I think this is because the Time has a timezone offset as well as the Date, and I really only need one of them to have the timezone offset.
Any suggestions on how to do this so that it will give me the correct Date/Time?
import java.sql.Time;
import java.util.Calendar;
import java.util.Date;
import org.apache.commons.lang.time.DateUtils;
public static Date combineDateTime(Date date, Time time)
{
if (date == null)
return null;
Date newDate = DateUtils.truncate(date, Calendar.DATE);
if (time != null)
{
Date t = new Date(time.getTime());
newDate = new Date(newDate.getTime() + t.getTime());
}
return newDate;
}
I would put both the Date and the Time into Calendar objects, and then use the various Calendar methods to extract the time values from the second object and put them into the first.
Calendar dCal = Calendar.getInstance();
dCal.setTime(date);
Calendar tCal = Calendar.getInstance();
tCal.setTime(time);
dCal.set(Calendar.HOUR_OF_DAY, tCal.get(Calendar.HOUR_OF_DAY));
dCal.set(Calendar.MINUTE, tCal.get(Calendar.MINUTE));
dCal.set(Calendar.SECOND, tCal.get(Calendar.SECOND));
dCal.set(Calendar.MILLISECOND, tCal.get(Calendar.MILLISECOND));
date = dCal.getTime();
Use Joda Time instead of Java's own Date classes when doing these types of things. It's a far superior date/time api that makes the sort of thing you are trying to do extremely easy and reliable.
#Paul Tomblin is a sure way to control the TimeZone issue, and I knew someone was going to throw "Joda Time" into the mix. The other answers are all good and more robust than the following hack:
If your application executes in the same TimeZone as is the default in the DB, you might be able to get away with the following:
If you skip this step:
Date t = new Date(time.getTime());
and use the java.sql.Time value directly, like:
newDate = new Date(newDate.getTime() + time.getTime());
the conversion to the default TimeZone won't be introduced - the java.sql.Time should contain the value as stored.
YMMV, caveat emptor, etc...
Assuming you know the time zone of the time being read from the database you need to use the ResultSet.getTime(String, Calendar) method having previously set the time zone on the Calendar. The JDBC driver will make the necessary adjustments to the time.
If all code is running serverside I'd strongly recommend standardizing on common time zone (probably UTC) for all times and converting as appropriate when displaying rendering in the GUI.
I'd also use JodaTime (http://joda-time.sourceforge.net), it'll save you headaches in the future.

Categories