How to convert getTime to seconds? - java

Can you please help in matter:
I have defined a variable which is:
Time from_time = rs.getTime("nfrm_time");
and it will read the values 7:15:00
How to convert this type to seconds?

Call getTime to get the number of milliseconds since January 1, 1970. Divide by 1000 to get it in seconds:
long unixTime = from_time.getTime() / 1000;
To get the number of seconds since 00:00 of the current day, use the
Calendar c = Calendar();
c.setTime(from_time);
long daySeconds = (c.get(Calendar.SECONDS) +
c.get(Calendar.MINUTES) * 60 +
c.get(Calendar.HOURS) * 3600);

long seconds = rs.getTime("nfrm_time").getTime() / 1000
Here's the explanation:
rs.getTime("nfrm_time") returns java.sql.Time which is actually a sub class of java.util.Date.
java.util.Date.getTime() returns time in milli seconds which we divide by 1000 to get seconds.
Note:
If you're looking for duration instead,
Calendar cal = Calendar.getInstance();
cal.setTime(rs.getTime("nfrm_time")); // set to the time returned by resultset
cal.set(0, 0, 0); // reset the year, month and date fields
Calendar cal2 = Calendar.getInstance();
cal2.set(0, 0, 0, 0, 0, 0); // reset all the fields, including time
long duration = ((cal.getTimeInMillis() - cal2.getTimeInMillis()) / 1000) + 1;

Try:
from_time.getTime() / 1000
This might work since:
The date components should be set to the "zero epoch" value of January 1, 1970 and should not be accessed.
This means that the date part is always the epoch day, which means the Time instance is represented by the number of milliseconds since the beginning of the day.

java.sql.Time inherits from java.util.Date which has a method getTime() which returns the number of milliseconds since January 1, 1970, 00:00:00 GMT.
So from_time.getTime()/1000 should do the trick.

Cleaner way is
Time from_time = Math.round(rs.getTime("nfrm_time")/1000);

To get the milliseconds:
long ms = from_time.getTime();

Related

Java how to compare LocalTime using only hours, minutes and seconds

I want to compare if 2 LocalTime are equal, but only using the hours, minutes and seconds, not with all the data of the variable, like milliseconds.
How can I accomplish that?
Considering the last edited version of your question, you can compare two instances of LocalTime by just hour, minute and second part this way:
LocalTime lt1 = LocalTime.now(); // usually contains seconds and subseconds
LocalTime lt2 = LocalTime.of(22, 48); // example with zero second part
boolean isEqualInSecondPrecision =
lt1.truncatedTo(ChronoUnit.SECONDS).equals(lt2.truncatedTo(ChronoUnit.SECONDS));
You can set the hours to the same in both with myTime.withHour(0), than you have left only the minutes and seconds that differ and you are able to come these 2 times.
Example:
time1 = ...
time2 = ...
if (time1.withHour(0).equals(time2.withHour(0))) {
System.out.println('Minutes and Seconds of time1 and time2 are equal!');
}
You can just set both nanos to one number to make them the same with each other, say, zero, to compare them.
LocalTime localTime1 = LocalTime.of(1, 2, 3, 100);
LocalTime localTime2 = LocalTime.of(1, 2, 3, 47);
if (localTime1.withNano(0).equals(localTime2.withNano(0))){
System.out.println("something");
}
Something like this
LocalTime t1=..
LocalTime t2=..
LocalTime.of(t1.getHour(), t1.getMinutes()).compareTo(LocalTime.of(t2.getHour(),t2.getMinutes());
with also seconds if u need of course

Is the TimeUnit class broken?

I noticed a strange behaviour of the TimeUnit class, so I created this minimal example to reproduce it.
long differenceInDays;
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
c1.setTimeInMillis(1466062306000l); // Thu Jun 16 2016 09:31:46 GMT+0200
c2.setTimeInMillis(1466028000000l); // Thu Jun 16 2016 00:00:00 GMT+0200
differenceInDays = TimeUnit.DAYS.convert(c2.getTimeInMillis() - c1.getTimeInMillis(), TimeUnit.MILLISECONDS);
System.out.println(differenceInDays); // obviously zero
c2.add(Calendar.DATE, +1);
differenceInDays = TimeUnit.DAYS.convert(c2.getTimeInMillis() - c1.getTimeInMillis(), TimeUnit.MILLISECONDS);
System.out.println(differenceInDays); // why zero and not one?
c2.add(Calendar.DATE, +1);
differenceInDays = TimeUnit.DAYS.convert(c2.getTimeInMillis() - c1.getTimeInMillis(), TimeUnit.MILLISECONDS);
System.out.println(differenceInDays); // suddenly a 1, but not a 2 like expected
It is obvious that the first time the difference is calculated it is 0, because not a whole day lies between the dates.
But the second time a whole day is added, so how can the difference be still 0?
Output:
001
I don't think this problem is daylight saving time or leap year related because I only do calculations within the same year, even month.
Here is a date to milliseconds calculator for you to check.
You can see better what's going on here with simple math:
c1 = 1466062306000
c2 = 1466028000000
d = 86400000 // one day
c2 - c1 = -34306000 // negative, but less than one day in magnitude
c2 - c1 + d = 52094000 // less than one day
c2 - c1 + d + d = 138494000 // more than one day, less than two days
The correct way to handle this, assuming you're using Java 8, is as follows:
// Decide what time zone you want to work in
ZoneId tz = ZoneId.of("Europe/Berlin");
// If you wanted the local time zone of the system,
// Use this instead:
// ZoneId tz = ZoneId.systemDefault();
// Get instants from the timestamps
Instant i1 = Instant.ofEpochMilli(1466062306000l);
Instant i2 = Instant.ofEpochMilli(1466028000000l);
// Get the calendar date in the specified time zone for each value
LocalDate d1 = i1.atZone(tz).toLocalDate();
LocalDate d2 = i2.atZone(tz).toLocalDate();
// Get the difference in days
long daysBetween = ChronoUnit.DAYS.between(d2, d1);
If your inputs are truly Calendar objects instead of timestamps, I'd suggest Calendar.toInstant() as described in the Legacy Date-Time Code guidance.
If you're using Java 7 or earlier, you will find similar capabilities from the Joda Time library.
if you really don't want to use any of these, and still do things the old (hard) way, then see this example.

Time difference in seconds gives me wrong answers

I have two date strings and I want to know how many seconds difference there is between them.
2014-05-19 16:37:36:690 // formattedDate
2014-05-19 19:38:00:000 // expString
I use the following code:
SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd HH:mm:ss:SSS");
Date d1 = null;
Date d2 = null;
d1 = sdf.parse(expString);
d2 = sdf.parse(formattedDate);
long diff = d1.getTime() - d2.getTime();
long exp = diff / 1000 % 60;
In this particular example exp is 23. What is the problem here?
.getTime() returns the time in milliseconds since January 1, 1970, 00:00:00 GMT. So diff has the time in milliseconds between the two dates.
long diff = d1.getTime() - d2.getTime();
// diff = 10882310
You user integer division to get to seconds, which drops the extra milliseconds.
long temp = diff / 1000;
// temp = 10823
Then you modulus by 60, which gets you seconds and ignores seconds that were attributed to minutes.
long exp = temp % 60;
// exp = 23
If you want the total time in seconds between the two dates, you don't want to do that last operation.
Don't use modulus division! Just use plain division:
long diff = d1.getTime() - d2.getTime();
long exp = diff / 1000;
Better yet, use the TimeUnit enum from the JDK:
long exp = TimeUnit.MILLISECONDS.toSeconds(d1.getTime() - d2.getTime());
Joda-Time offers a Seconds class to just what you want.
The Joda-Time library also has classes to represent spans of time: Duration, Interval, and Period. You don’t strictly need them for this specific question, but they will be handy for related work.
Below is some untested code off the top of my head.
For simplicity, convert your strings to strict ISO 8601 format. Replace the SPACE with a T.
String inputStart = "…".replace( " ", "T" );
// same for stop
Create date-time objects. Explicitly assign a time zone by which to parse those strings. Are that UTC?
DateTime startDateTime = new DateTime( inputStart, DateTimeZone.UTC );
// repeat for stop
long secs = Seconds.secondsBetween( startDateTime, stopDateTime ).getSeconds();

How do I increment a java.sql.Timestamp by 14 days?

I have an app that takes a Timestamp as a boundary for the start date and end date of a sql selection, I want to populate a hashmap with weeks this year since the first monday of the year as the values and the week number as the keys. I'm finding it really hard to work with timestamps and I don't feel very good about adding 86,400,000 seconds to it to increment the day, as this doesn't account for the leap days, hours, seconds.
I plan on adding 13 days 23 hours, 59 minutes and 59 seconds to it so that I can lookup the start date in the map by the week as the key, then use the start date to get the end date.
So I'm looking to try to get something like this:
Week startDate endDate
1 2011-01-03 00:00:00 2011-01-16 23:59:59
2 2011-01-17 00:00:00 2011-01-30 23:59:59
With the first two columns in the Map and the last one being calculated after looking it up. How do I safely increment a java.sql.Timestamp?
java.sql.Timestamp ts = ...
Calendar cal = Calendar.getInstance();
cal.setTime(ts);
cal.add(Calendar.DAY_OF_WEEK, 14);
ts.setTime(cal.getTime().getTime()); // or
ts = new Timestamp(cal.getTime().getTime());
This will correctly cater for daylight-time transitions in your default Timezone. You can tell the Calendar class to use a different Timezone if need be.
It worth noting that 14 days is not always 14 * 24 * 3600 seconds. When you have daylight savings, this can be an hour shorter or longer. Historically it can be much more complex than that.
Instead I would suggest using JodaTime or the Calendar to perform the time zone dependant calculation.
Java 8
Timestamp old;
ZonedDateTime zonedDateTime = old.toInstant().atZone(ZoneId.of("UTC"));
Timestamp new = Timestamp.from(zonedDateTime.plus(14, ChronoUnit.DAYS).toInstant());
private Long dayToMiliseconds(int days){
Long result = Long.valueOf(days * 24 * 60 * 60 * 1000);
return result;
}
public Timestamp addDays(int days, Timestamp t1) throws Exception{
if(days < 0){
throw new Exception("Day in wrong format.");
}
Long miliseconds = dayToMiliseconds(days);
return new Timestamp(t1.getTime() + miliseconds);
}
Timestamp my14DaysAfter = Timestamp.valueOf(myTimestamp.toLocalDateTime().plusDays(14));

milliseconds until next 5th second

So I want to do some monitoring and I want it to be on every fifth minute, so for example if the application starts at 1:47 monitor everything until 1:50 and then reset. I currently have this working for hour but I need to cut it down to every fifth minute and I'm having a little trouble coming up with the math.
I get all of the current time information
Calendar currentCalendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
long currentTimeInMillis = currentCalendar.getTimeInMillis();
int hr = currentCalendar.get(Calendar.HOUR_OF_DAY);
int min = currentCalendar.get(Calendar.MINUTE);
int sec = currentCalendar.get(Calendar.SECOND);
int millis = currentCalendar.get(Calendar.MILLISECOND);
Now I need to find the next fifth minute, for hour I have this which works.
millisUntilNextHour = currentTimeInMillis + ((60L - min) * SECONDS_IN_MINUTE * 1000L) + ((60 - sec) * 1000L) + (1000L - millis);
Can anybody think of a way similar to above to get the milliseconds to the closest fifth minute?
Every fifth minute is 5 minutes * 60 seconds/minute * 1000 millisecond/second = 300,000 milliseconds.
Try this then:
millisUntilNextHour = (min*60*1000 + sec*1000 + millis + 299999)/300000*300000 - (min*60*1000 + sec*1000 + millis)
The +299999)/300000*300000 rounds up to the nearest 300,000. Then you get the difference between that and the current millisecond to find out how many milliseconds you are away from it.
Using the same approach as described in the question:
Calendar currentCalendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
int min = currentCalendar.get(Calendar.MINUTE);
currentCalendar.set(Calendar.MINUTE, 5 * (min / 5 + 1));
currentCalendar.set(Calendar.SECOND, 0);
currentCalendar.set(Calendar.MILLISECOND, 0);
millisUntilNextHour = currentCalendar.getTimeInMillis();
Update:
Reverted to my initial variant. It works as a charm. Lenient calendar (currentCalendar is lenient) works perfectly as expected when setting as minutes value greater than 60. From javadoc:
/**
* With lenient interpretation, a date such as "February 942, 1996" will be
* treated as being equivalent to the 941st day after February 1, 1996.
* With strict (non-lenient) interpretation, such dates will cause an exception to be
* thrown. The default is lenient.
*/
Why not use Quartz, which can handle this sort of thing easily. For the above you could specify a cron-type expression.
It may seem a bit heavyweight for your initial requirements but it's scaleable so it'll handle any future requirements.
Add five minutes to the current time, then set the seconds and millis to zero.
Note that the important thing is to use the .add(field, amount) method, as it will roll correctly into the next hour, etc. (including daylight savings, etc).
Calendar currentCalendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
// store off the milliseconds from the epoch
int startTime = currentCalendar.getTime().getTime();
currentCalendar.add(Calendar.MINUTE, 5);
currentCalendar.set(Calendar.SECOND, 0);
currentCalendar.set(Calendar.MILLISECOND, 0);
// calculate the milliseconds difference.
int difference = currentCalendar.getTime().getTime() - startTime;
System.out.println("The number of milliseconds till " + currentCalendar.getTime() + " is " + startTime);

Categories