how to add series of sql time values in java - java

I have a ResultSet of of Time objects that are the differences between two times. They are in the minute to second range for example "00:01:12" or "00:00:22"
How do I add these java.sql.time values together to be a sum of time?
Thanks!

public Date sumDates(String[] dateStrings, DateFormat df) {
int secs=0, mins=0, hrs=0;
Calendar calendar = Calendar.getInstance();
for (int i=0; i<dateStrings.length; i++) {
String dateString = dateStrings[i];
Date date = (Date) df.parse(dateString);
calendar.setTime(date);
secs += calendar.get(Calendar.SECOND);
mins += calendar.get(Calendar.MINUTE);
hrs += calendar.get(Calendar.HOUR);
}
calendar.set(0, 0, 0, hrs, mins, secs);
return calendar.getTime();
}
Example of usage:
String[] dateStrings = { "00:01:12", "00:00:22" };
DateFormat df = new SimpleDateFormat("hh:mm:ss");
Date total = sumDates(dateStrings, df);
System.out.println(df.format(total)); //output: 00:01:34

java.sql.Time is designed to represent points in time, not durations, so you can't do arithmetic with objects of that class directly. I'm somewhat surprised there's not a java.sql analog of Duration, since some RDBMSes provide the distinction. Anyway, you can always do it manually, with (semi-pseudo)code like this:
int totalSeconds = 0;
for (java.sql.Time s : myResultSet) {
totalSeconds += s.getHours()*3600 + s.getMinutes()*60 + s.getSeconds();
}

Related

Calculating time between datetimes

Let's say I have two datetimes, 30-11-2015 10:00 and 02-12-2015 15:00. I also have two times, 07:00 and 22:00. How could I calculate the amount of time passed between the two date/times that was within the second times? Using Calendar object? It seems simple but its boggling my mind.
Since none of the other answers include runnable code, I can't tell if they solve the problem or not.
To calculate the duration of a time range within a date range, you have to:
Split the date range into multiple date ranges, each spanning no more than one day.
Calculate the time range within each day date range
Taking the example date range from the question. 30-11-2015 10:00 and 02-12-2015 15:00, we generate the following split day date ranges:
30-11-2015 10:00 - 30-11-2015 24:00
01-12-2015 00:00 - 01-12-2015 24:00
02-12-2015 00:00 - 02-12-2015 15:00
Now, we can apply the time range of 7:00 - 22:00 to each of the split day date ranges.
30-11-2015 10:00 - 30-11-2015 24:00 -> 12 hours
01-12-2015 00:00 - 01-12-2015 24:00 -> 15 hours
02-12-2015 00:00 - 02-12-2015 15:00 -> 8 hours
For a total of 35 hours. The actual calculation would probably be in minutes instead of hours.
Edited to add: I created a Time and a TimeRange class to hold the time and a day time range, respectively. I used the java.util.Date, although I had to create my own increment a day method.
I put all of the classes together so I could post this easier. The classes should be put in separate files.
package com.ggl.testing;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class TimeRangeTest {
private static final SimpleDateFormat inputDateFormat = new SimpleDateFormat(
"dd-MM-yyyy");
public static void main(String[] args) {
TimeRangeTest test = new TimeRangeTest();
int minutes = test.calculateTotalMinutes("30-11-2015 10:00",
"02-12-2015 15:00", "07:00", "22:00");
System.out.println(minutes + " minutes, " + (minutes / 60) + " hours");
}
public int calculateTotalMinutes(String startDateTimeString,
String endDateTimeString, String startTimeString,
String endTimeString) {
try {
List<TimeRange> timeRanges = generateTimeRanges(
startDateTimeString, endDateTimeString);
return calculateTimeRange(timeRanges, startTimeString,
endTimeString);
} catch (ParseException e) {
e.printStackTrace();
return 0;
}
}
private List<TimeRange> generateTimeRanges(String startDateTimeString,
String endDateTimeString) throws ParseException {
Date startDate = inputDateFormat.parse(startDateTimeString.substring(0,
10));
Time startTime = new Time(startDateTimeString.substring(11));
Date endDate = inputDateFormat
.parse(endDateTimeString.substring(0, 10));
Time endTime = new Time(endDateTimeString.substring(11));
List<TimeRange> timeRanges = new ArrayList<>();
Date currentDate = new Date(startDate.getTime());
Time currentTime = new Time(startTime);
Time eodTime = new Time("24:00");
while (currentDate.compareTo(endDate) < 0) {
TimeRange timeRange = new TimeRange(currentDate, currentTime,
eodTime);
timeRanges.add(timeRange);
currentTime = new Time("00:00");
currentDate = new Date(currentDate.getTime() + 24L * 60L * 60L
* 1000L);
}
TimeRange timeRange = new TimeRange(currentDate, currentTime, endTime);
timeRanges.add(timeRange);
return timeRanges;
}
private int calculateTimeRange(List<TimeRange> timeRanges,
String startTimeString, String endTimeString) {
int count = 0;
Time startTime = new Time(startTimeString);
Time endTime = new Time(endTimeString);
for (TimeRange timeRange : timeRanges) {
Time sodTime = new Time(timeRange.getStartTime());
Time eodTime = new Time(timeRange.getEndTime());
Time sTime = startTime.max(sodTime);
Time eTime = endTime.min(eodTime);
count += eTime.difference(sTime);
}
return count;
}
public class TimeRange {
private final SimpleDateFormat inputDateFormat = new SimpleDateFormat(
"dd-MM-yyyy");
private final Date date;
private final Time startTime;
private final Time endTime;
public TimeRange(Date date, Time startTime, Time endTime) {
this.date = date;
this.startTime = startTime;
this.endTime = endTime;
}
public Date getDate() {
return date;
}
public Time getStartTime() {
return startTime;
}
public Time getEndTime() {
return endTime;
}
#Override
public String toString() {
return inputDateFormat.format(getDate()) + " "
+ startTime.toString() + " -> " + endTime.toString();
}
}
public class Time {
private final int minutesPastMidnight;
public Time(String timeString) {
int hours = Integer.valueOf(timeString.substring(0, 2));
int minutes = Integer.valueOf(timeString.substring(3, 5));
this.minutesPastMidnight = hours * 60 + minutes;
}
public Time(Time time) {
this.minutesPastMidnight = time.getMinutesPastMidnight();
}
private int getMinutesPastMidnight() {
return minutesPastMidnight;
}
public int difference(Time time) {
return this.getMinutesPastMidnight()
- time.getMinutesPastMidnight();
}
public Time min(Time time) {
return (difference(time) > 0) ? time : this;
}
public Time max(Time time) {
return (difference(time) > 0) ? this : time;
}
#Override
public String toString() {
int hours = minutesPastMidnight / 60;
int minutes = minutesPastMidnight - (hours * 60);
return String.format("%02d:%02d", hours, minutes);
}
}
}
If you use java8, you can use LocalDateTime. Then your code could looks like this:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
LocalDateTime dateTimeStart = LocalDateTime.parse("2015-10-01 10:00", formatter);
LocalDateTime dateTimeEnd = LocalDateTime.parse("2015-10-02 10:00", formatter);
long seconds = Duration.between(dateTimeStart, dateTimeEnd).getSeconds();
Or LocalTime if you have only time. Then it could looks like this:
LocalTime timeStart = LocalTime.parse("07:00");
LocalTime timeEnd = LocalTime.parse("22:00");
long seconds = Duration.between(timeStart, timeEnd).getSeconds();
If you can't use java8, you can get the number of milliseconds since 1970-01-01 00:00:00 to your date using getTime() method and do simple subtraction operation, like this:
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date dateStart = simpleDateFormat.parse("2015-10-01 10:00");
Date dateEnd = simpleDateFormat.parse("2015-10-02 10:00");
long milliseconds = dateEnd.getTime() - dateStart.getTime();
long seconds = resultInMillisecond / 1000;

How to calculate a full days difference between two dates considering daylight savings in java

I need to get the full days between two dates in java (the dates are given in Date type) .
For example:
01/01/2015/12:00:00 - 01/02/2015/11:59:00 isn't a full day
and i need to consider daylight savings.
I know that jodatime lib does that but i reached the 65k method limit and i cant use jodatime lib.
i tried the millisecond diff way and the while loop that uses the "before" method:
Android/Java - Date Difference in days
I manage to figure it out:
i used some of this code - https://stackoverflow.com/a/28865648/3873513
and added some of mine:
public static int calcDaysDiff(Date day1, Date day2) {
Date d1 = new Date(day1.getTime());
Date d2 = new Date(day2.getTime());
Calendar date1 = Calendar.getInstance();
date1.setTime(d1);
Calendar date2 = Calendar.getInstance();
date2.setTime(d2);
//checks if the start date is later then the end date - gives 0 if it is
if (date1.get(Calendar.YEAR) >= date2.get(Calendar.YEAR)) {
if (date1.get(Calendar.DAY_OF_YEAR) >= date2.get(Calendar.DAY_OF_YEAR)) {
return 0;
}
}
//checks if there is a daylight saving change between the two dates
int offset = calcOffset(d1, d2);
if (date1.get(Calendar.YEAR) > date2.get(Calendar.YEAR)) {
//swap them
Calendar temp = date1;
date1 = date2;
date2 = temp;
}
return calcDaysDiffAux(date1, date2) + checkFullDay(date1, date2, offset);
}
// check if there is a 24 hour diff between the 2 dates including the daylight saving offset
public static int checkFullDay(Calendar day1, Calendar day2, int offset) {
if (day1.get(Calendar.HOUR_OF_DAY) <= day2.get(Calendar.HOUR_OF_DAY) + offset) {
return 0;
}
return -1;
}
// find the number of days between the 2 dates. check only the dates and not the hours
public static int calcDaysDiffAux(final Calendar day1, final Calendar day2) {
Calendar dayOne = (Calendar) day1.clone(),
dayTwo = (Calendar) day2.clone();
if (dayOne.get(Calendar.YEAR) == dayTwo.get(Calendar.YEAR)) {
return Math.abs(dayOne.get(Calendar.DAY_OF_YEAR) - dayTwo.get(Calendar.DAY_OF_YEAR));
} else {
int extraDays = 0;
while (dayTwo.get(Calendar.YEAR) > dayOne.get(Calendar.YEAR)) {
dayTwo.add(Calendar.YEAR, -1);
// getActualMaximum() important for leap years
extraDays += dayTwo.getActualMaximum(Calendar.DAY_OF_YEAR);
}
return extraDays - day1.get(Calendar.DAY_OF_YEAR) + day2.get(Calendar.DAY_OF_YEAR);
}
}
public class DateDiff {
public static void main(String[] av) {
SimpleDateFormat myFormat = new SimpleDateFormat("MM/dd/yyyy/HH:mm:ss");
String inputString1 = "01/01/2015/12:00:00";
String inputString2 = "01/02/2015/11:59:00";
try {
Date date1 = myFormat.parse(inputString1);
Date date2 = myFormat.parse(inputString2);
long diff = date2.getTime() - date1.getTime(); // Calculate the different
int days = (int) (diff / (1000*60*60*24)); // This convert milliseconds to days
System.out.println ("Days differ: " + days);
} catch (Exception e) {
e.printStackTrace();
}
}
}
The following code will calculate the two dates given, the result print is:
Days differ: 0

How can I check if it is between 2pm and 1am new york time?

I need to check if the time in new york time zone is between 2pm and 1 am but i am not sure how to select the timezone or what to do next
String string1 = "14:00:00";
Date time1 = new SimpleDateFormat("HH:mm:ss").parse(string1);
Calendar calendar1 = Calendar.getInstance();
calendar1.setTime(time1);
String string2 = "01:00:00";
Date time2 = new SimpleDateFormat("HH:mm:ss").parse(string2);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(time2);
calendar2.add(Calendar.DATE, 1);
If you're interested in whether the current time is "after or equal to 2pm, or before 1am" then don't need to use string parsing at all. You could use:
TimeZone zone = TimeZone.getTimeZone("America/New_York");
Calendar calendar = new GregorianCalendar(zone);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
if (hour < 1 || hour >= 14) {
...
}
That's assuming you do want it to match 3pm, but you don't want it to match 8am, for example. That's "between 2pm and 1am" in my view, as per your title.
If you're using Java 8, I'd suggest using LocalTime instead, via ZonedDateTime:
private static final LocalTime EARLY_CUTOFF = LocalTime.of(1, 0);
private static final LocalTime LATE_CUTOFF = LocalTime.of(14, 0);
ZoneId zone = ZoneId.of("America/New_York");
LocalTime time = ZonedDateTime.now(zone).toLocalTime();
if (time.compareTo(EARLY_CUTOFF) < 0 && time.compareTo(LATE_CUTOFF) >= 0) {
...
}
Calendar calNewYork = Calendar.getInstance();
calNewYork.setTimeZone(TimeZone.getTimeZone("America/New_York"));
int curr_hour = calNewYork.get(Calendar.HOUR_OF_DAY);
System.out.println(curr_hour < 1 || curr_hour >= 14);

How to get time in 12hr format from a long value in java

I have a long value which have values as given bellow,
e.g.
timeInLong = 1000 (which means 10:00 AM)
timeInLong = 1337 (which means 01:37 PM)
I need a smart way to convert above types of values and get time as 10:00AM and 01:37PM in string format.
Can someone please tell me how to do this?
Code -
Long timeInLong = 1000l;
SimpleDateFormat dateFormat = new SimpleDateFormat("HHmm");
Date date = dateFormat.parse(Long.toString(timeInLong));
System.out.println(new SimpleDateFormat("hh:mm a").format(date));
Result -
10:00 AM
Try:
SimpleDateFormat readerFormat = "HHmm";
SimpleDateFormat writerFormat = "hh:mma";
Date date = readerFormat.parse(Long.toString(timeInLong));
String toPrint = writerFormat.format(date);
I would do something like this:
SimpleDateFormat formatA = new SimpleDateFormat("hhmm");
SimpleDateFormat formatB = new SimpleDateFormat("hh:mm a");
Date intermediate = formatA.parse(String.valueOf(1337));
String result = formatB.format(intermediate);
int timeInLong = 1337;
Calendar c = Calendar.getInstance();
c.set(Calendar.MINUTE, timeInLong % 100);
c.set(Calendar.HOUR_OF_DAY, timeInLong / 100);
System.out.println(new SimpleDateFormat("HH:mm a", Locale.US).format(c.getTime()));
Alternative and efficient oneliner if you want to avoid the SimpleDateFormat import:
String toTimeString(long time) {
return ((time < 1300) ? time / 100 : time / 100 - 12)
+ ":" + time % 100
+ ((time < 1200) ? " AM" : " PM");
}
It seams too easy, but what about:
int hours = timeInLong / 100;
int minutes = timeInLong % 100;
boolean isPM = false;
if (hours > 12) {
isPM = true
}
if (hours > 13) {
hours -= 12;
}
String result = String.format("%02d:%02d %s", hours, minutes, (isPM ? "PM" : "AM"));
Did I miss something?

Display curentdate and last 5 days dates in java

I want to display the current date and last 5 days dates
2013/04/24
2013/04/23
2013/04/22
2013/04/21
2013/04/20
I have code as below..
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
Calendar cal = Calendar.getInstance();
Date date=cal.getTime();
for (int i=0;i<5;i++){
cal.add(Calendar.DAY_OF_MONTH,-1);
date=cal.getTime();
String reportDate = sdf.format(date);
System.out.println("reportDate :" + reportDate);
}
Here i am getting output like below..
reportDate :2013/04/23
reportDate :2013/04/22
reportDate :2013/04/21
reportDate :2013/04/20
reportDate :2013/04/19
but i want last five days dates including current date...can any one help?
Try this!!
public static void getDate(){
GregorianCalendar cal = new GregorianCalendar();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
int day = cal.get(GregorianCalendar.DAY_OF_MONTH);
for(int i=day; i > (day-5); i--){
cal.set(GregorianCalendar.DAY_OF_MONTH, i);
Date date = cal.getTime();
System.out.println(sdf.format(date));
}
}
v 2.0
public static void getDate1(){
GregorianCalendar cal = new GregorianCalendar();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
cal.set(2013, 0, 1); // this is extreme case!!!
int day = cal.get(GregorianCalendar.DAY_OF_MONTH);
int month = cal.get(GregorianCalendar.MONTH);
int year = cal.get(GregorianCalendar.YEAR);
for(int i=day; i > (day-5); i--){
cal.set(year, month, i);
Date date = cal.getTime();
System.out.println(sdf.format(date));
}
}
This is the Output:
2013/01/01
2012/12/31
2012/12/30
2012/12/29
2012/12/28
The problem is this line:
cal.add(Calendar.DAY_OF_MONTH,-i);
Specifically the -i part. In the first iteration, i is 0 so you don't subtract any days. In the next you subtract one day, so you get the 23rd. In the next, you subtract two days, so you get the 21st, and so on.
You want to print out the initial date, then loop four times subtracting one day each in each iteration, so:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
Calendar cal = Calendar.getInstance();
Date date = cal.getTime();
String reportDate = sdf.format(date);
System.out.println("reportDate :" + reportDate);
for (int i = 0; i < 4; i++) {
cal.add(Calendar.DAY_OF_MONTH, -1);
date = cal.getTime();
reportDate = sdf.format(date);
System.out.println("reportDate :" + reportDate);
}
Your subtracting the value of i in each iteration. And i increases by 1 each iteration. You probably just want to subtract 1 regardless of i.
cal.add(Calendar.DAY_OF_MONTH, -1);
Edit
Or maybe even a better solution
cal.roll(Calendar.DAY_OF_MONTH, false);

Categories

Resources