How to get time Interval of date from Day , Hour and Minutes - java

I have variables which store the values
int day = Calender.SATURDAY;
int hour = 18;
int minutes = 33;
How can I convert this to Date? so
How I can find the time difference in milliseconds from Current date time?
Cases :
If the current date, time pass already passed,
for example: If the current day is Saturday, and now time is 19: 00, than get the next week date time interval.
If the current day is Saturday, and now time is 18: 30,
(the time interval should be 180000 milliseconds = 3 minutes).
How can I do this in android?
Please help me with finding the proper solution for this problem.

Create a Calendar (Calendar.getInstance()), set your fields (cal.set(Calendar.DAY, day), etc.) and then call getTime() on it - that will return a Date.

For a proper solution I strongly advise to use the modern functions provided by java.time instead of the deprecated java.util. Read this post and Convert java.util.Date to what “java.time” type? to understand the package. How to get java.time on android pre API 26 is described here: How to use ThreeTenABP in Android Project
If you have read those you can solve your problem along the lines of this example:
public void dateStuff() {
int day = DayOfWeek.SATURDAY.getValue();
int hour = 18;
int minutes = 33;
LocalDateTime now = LocalDateTime.now();
int dayDifference = now.getDayOfWeek().getValue() - day;
LocalDateTime date = LocalDateTime.of(now.getYear(), now.getMonth(), now.getDayOfMonth() - dayDifference, hour, minutes);
long timeDifferenceNano = Duration.between(now, date).getNano();
long timeDifference = TimeUnit.NANOSECONDS.toMillis(timeDifferenceNano);
if (timeDifference > TimeUnit.MINUTES.toMillis(3)) {
//do stuff
}
}
Unfortunately I did not really understand when the two cases come into play, but I'm sure you can take it from here.

Related

How to transfer Date.getTime() to hours and calculating difference

I have a program that is intaking an "AM" "PM" time and calculating out the hours in the day equivalent (in 24 hour format). For some reason it parses and calculates the time I input to the incorrect 24 hour equivalent (ie 5:00 pm comes to equal 22)
System.out.print("Enter the end time (HH:MM am): ");
endTime = input.nextLine();
Date ETime = time_to_date.parse(endTime);
Class method
public int get_Family_A_Calulation(Date STime, Date ETime) {
Date startTimeCalc = STime, endTimeCalc = ETime;
int pay = 0, hoursWorked, StartHour, EndHour;
StartHour = ((((int) startTimeCalc.getTime()) / 1000) / 60) / 60;
EndHour = ((((int) endTimeCalc.getTime()) / 1000) / 60) / 60;
pay = hoursWorked * 15;
return pay;
}
I am not sure where my error is can anyone give me advice on how to correct this error?
Use the latest classes available fron java8
LocalDateTime now = LocalDateTime.now();
System.out.println(now.getHour());
The actual data behind Date is milliseconds since the epoch. Any hour or time representation is based on the calendar date portion and takes into account timezone and daylight savings.
Regardless of what you do, there will be calculation issues across days, etc.
As suggested by Scary Wombat, use the new classes in java.time package. For your specific case, you need a LocalTime as the code is trying to represent a time element (hours, minutes, seconds, etc) without consideration for Date, TimeZone, etc.
https://docs.oracle.com/javase/8/docs/api/java/time/LocalTime.html

Java 8 calculate months between two dates

NOTE THIS IS NOT A DUPLICATE OF EITHER OF THE FOLLOWING
Calculating the difference between two Java date instances
calculate months between two dates in java [duplicate]
I have two dates:
Start date: "2016-08-31"
End date: "2016-11-30"
Its 91 days duration between the above two dates, I expected my code to return 3 months duration, but the below methods only returned 2 months. Does anyone have a better suggestion? Or do you guys think this is a bug in Java 8? 91 days the duration only return 2 months.
Thank you very much for the help.
Method 1:
Period diff = Period.between(LocalDate.parse("2016-08-31"),
LocalDate.parse("2016-11-30"));
Method 2:
long daysBetween = ChronoUnit.MONTHS.between(LocalDate.parse("2016-08-31"),
LocalDate.parse("2016-11-30"));
Method 3:
I tried to use Joda library instead of Java 8 APIs, it works. it loos will return 3, It looks like Java duration months calculation also used days value. But in my case, i cannot use the Joda at my project. So still looking for other solutions.
LocalDate dateBefore= LocalDate.parse("2016-08-31");
LocalDate dateAfter = LocalDate.parse("2016-11-30");
int months = Months.monthsBetween(dateBefore, dateAfter).getMonths();
System.out.println(months);
Since you don't care about the days in your case. You only want the number of month between two dates, use the documentation of the period to adapt the dates, it used the days as explain by Jacob. Simply set the days of both instance to the same value (the first day of the month)
Period diff = Period.between(
LocalDate.parse("2016-08-31").withDayOfMonth(1),
LocalDate.parse("2016-11-30").withDayOfMonth(1));
System.out.println(diff); //P3M
Same with the other solution :
long monthsBetween = ChronoUnit.MONTHS.between(
LocalDate.parse("2016-08-31").withDayOfMonth(1),
LocalDate.parse("2016-11-30").withDayOfMonth(1));
System.out.println(monthsBetween); //3
Edit from #Olivier Grégoire comment:
Instead of using a LocalDate and set the day to the first of the month, we can use YearMonth that doesn't use the unit of days.
long monthsBetween = ChronoUnit.MONTHS.between(
YearMonth.from(LocalDate.parse("2016-08-31")),
YearMonth.from(LocalDate.parse("2016-11-30"))
)
System.out.println(monthsBetween); //3
Since Java8:
ChronoUnit.MONTHS.between(startDate, endDate);
//Backward compatible with older Java
public static int monthsBetween(Date d1, Date d2){
if(d2==null || d1==null){
return -1;//Error
}
Calendar m_calendar=Calendar.getInstance();
m_calendar.setTime(d1);
int nMonth1=12*m_calendar.get(Calendar.YEAR)+m_calendar.get(Calendar.MONTH);
m_calendar.setTime(d2);
int nMonth2=12*m_calendar.get(Calendar.YEAR)+m_calendar.get(Calendar.MONTH);
return java.lang.Math.abs(nMonth2-nMonth1);
}
The documentation of Period#between states the following:
The start date is included, but the end date is not.
Furthermore:
A month is considered if the end day-of-month is greater than or equal to the start day-of-month.
Your end day-of-month 30 is not greater than or equal to your start day-of-month 31, so a third month is not considered.
Note the parameter names:
public static Period between​(LocalDate startDateInclusive, LocalDate endDateExclusive)
To return 3 months, you can increment the endDateExclusive by a single day.
In case you want stick to java.time.Period API
As per java.time.Period documentation
Period between(LocalDate startDateInclusive, LocalDate endDateExclusive)
where
#param startDateInclusive the start date, inclusive, not null
#param endDateExclusive the end date, exclusive, not null
So it is better to adjust your implementation to make your end date inclusive and get your desired result
Period diff = Period.between(LocalDate.parse("2016-08-31"),
LocalDate.parse("2016-11-30").plusDays(1));
System.out.println("Months : " + diff.getMonths());
//Output -> Months : 3
You have to be careful, never use LocalDateTime to calculate months between two dates the result is weird and incorrect, always use LocalDate !
here's is some code to prove the above:
package stack.time;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
public class TestMonthsDateTime {
public static void main(String[] args) {
/**------------------Date Time----------------------------*/
LocalDateTime t1 = LocalDateTime.now();
LocalDateTime t2 = LocalDateTime.now().minusMonths(3);
long dateTimeDiff = ChronoUnit.MONTHS.between(t2, t1);
System.out.println("diff dateTime : " + dateTimeDiff); // diff dateTime : 2
/**-------------------------Date----------------------------*/
LocalDate t3 = LocalDate.now();
LocalDate t4 = LocalDate.now().minusMonths(3);
long dateDiff = ChronoUnit.MONTHS.between(t4, t3);
System.out.println("diff date : " + dateDiff); // diff date : 3
}
}
My 2%
This example checks to see if the second date is the end of that month. If it is the end of that month and if the first date of month is greater than the second month date it will know it will need to add 1
LocalDate date1 = LocalDate.parse("2016-08-31");
LocalDate date2 = LocalDate.parse("2016-11-30");
long monthsBetween = ChronoUnit.MONTHS.between(
date1,
date2);
if (date1.isBefore(date2)
&& date2.getDayOfMonth() == date2.lengthOfMonth()
&& date1.getDayOfMonth() > date2.getDayOfMonth()) {
monthsBetween += 1;
}
After the short investigation, still not totally fix my question, But I used a dirty solution to avoid return the incorrect duration. At least, we can get the reasonable duration months.
private static long durationMonths(LocalDate dateBefore, LocalDate dateAfter) {
System.out.println(dateBefore+" "+dateAfter);
if (dateBefore.getDayOfMonth() > 28) {
dateBefore = dateBefore.minusDays(5);
} else if (dateAfter.getDayOfMonth() > 28) {
dateAfter = dateAfter.minusDays(5);
}
return ChronoUnit.MONTHS.between(dateBefore, dateAfter);
}
The Java API response is mathematically accurate according to the calendar. But you need a similar mechanism, such as rounding decimals, to get the number of months between dates that matches the human perception of the approximate number of months between two dates.
Period period = Period.between(LocalDate.parse("2016-08-31"), LocalDate.parse("2016-11-30"));
long months = period.toTotalMonths();
if (period.getDays() >= 15) {
months++;
}

Android converting the time in milliseconds

I have checked questions about converting time in milliseconds and I followed all answers, but I am still getting the wrong number of hours, although the minutes and seconds are ok.
In my application the user has to select a time from a TimePickerDialog and set the time in the textview. It will show for example 01:30 in a clock. It will show me 502125000222:30:00
My code TimePickerDialog:
TimePickerDialog timePickerDialog = new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
Calendar mycalendar = Calendar.getInstance();
mycalendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
mycalendar.set(Calendar.MINUTE, minute);
mycalendar.set(Calendar.SECOND, 0);
long times = mycalendar.getTimeInMillis();
// hmsTimeFormatter is a method return time format
String timerRemaind = hmsTimeFormatter(times);
//tv_remaindertime is TextView
tv_remaindertime.setText(timerRemaind);
............
And this hmsTimeFormatter method that converts milliseconds:
private String hmsTimeFormatter(long milliSeconds) {
String hms = String.format("%02d:%02d:%02d",
TimeUnit.MILLISECONDS.toHours(milliSeconds),
TimeUnit.MILLISECONDS.toMinutes(milliSeconds) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(milliSeconds)),
TimeUnit.MILLISECONDS.toSeconds(milliSeconds) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(milliSeconds)));
return hms;
}
To understand what's happening:
Calendar.getInstance() creates a Calendar with the current date/time in the JVM default timezone
You set the hour, minutes and seconds (to 01:30:00 I suppose)
You call getTimeInMillis(), that returns the number of milliseconds since unix epoch (1970-01-01T00:00Z)
Then you use this milliseconds value with TimeUnit, but that's not what you need. TimeUnit will treat the number of milliseconds as an amount of time, but what you need is a time of the day:
a time of the day is a specific moment in a day, such as "10 AM" or "05:30 PM".
an amount of time is just, well, an amount of elapsed time, such as "10 minutes and 45 seconds", or "2 years, 4 months, 5 days and 17 hours", but it's not attached to a specific point in time ("10 minutes relative to what?"); it's just the amount of time, by itself.
Although both concepts might use the same words ("hours", "minutes", "seconds", etc), they're not the same thing.
TimeUnit deals with amounts of time, so it does conversions like "1000 seconds is equivalent to how many minutes?".
Example: TimeUnit.MILLISECONDS.toHours(value) returns the number of hours equivalent to value milliseconds (not the time of the day). As the value you're using is the result of getTimeInMillis(), you're getting the total number of hours since January 1970.
By using the result of getTimeInMillis() (which represents a specific point in time) with TimeUnit, you're misusing the value, treating like it was an amount of time.
To format a date, you can use a SimpleDateFormat:
Calendar mycalendar = Calendar.getInstance();
mycalendar.set(Calendar.HOUR_OF_DAY, 1);
mycalendar.set(Calendar.MINUTE, 30);
mycalendar.set(Calendar.SECOND, 0);
// format: hour:minute:second
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
String hms = sdf.format(mycalendar.getTime()); // 01:30:00
With this, hms will have the value 01:30:00. Check the javadoc to know what the format HH:mm:ss means, so you can change it in case you need a different format (If you want just 01:30, for example, the format will be HH:mm).
Java new Date/Time API
The old classes (Date, Calendar and SimpleDateFormat) have lots of problems and design issues, and they're being replaced by the new APIs.
In Android you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. To make it work, you'll also need the ThreeTenABP (more on how to use it here).
First you create a org.threeten.bp.LocalTime (a class that represents a time of the day), then you format it with a org.threeten.bp.format.DateTimeFormatter:
// create time for 01:30
LocalTime time = LocalTime.of(1, 30);
// format: hour:minute:second
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("HH:mm:ss");
String hms = fmt.format(time);
System.out.println(hms); // 01:30:00
Also, check the javadoc for all available formats.
Hello how about using a powerful Library? its very easy and useful,
it`s saves you from many line
Joda-Time
Usage :
Gradle configuration:
compile 'joda-time:joda-time:2.9.9'
for more information and documentation :
https://github.com/JodaOrg/joda-time
http://www.joda.org/joda-time/
Happy Coding!
If I understand you right, you want to have millis converted to HH:mm:ss.
For that we use SimpleDateFormat
private String hmsTimeFormatter(long milliSeconds) {
Date date = new Date(milliSeconds);
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
return format.format(date);
}
Just Try it and change the format Syntax to the one you like

Issues Converting String dates into Long values and performing calculations

I have a map of string values which represent down times for different components.
dependencyMap.put ("sut", "14:26:12,14:27:19,00:01:07;15:01:54,15:02:54,00:01:00;15:44:30,15:46:30,00:02:00;16:10:30,16:11:30,00:01:00");
dependencyMap.put ("jms", "14:26:12,14:28:12,00:02:00;15:10:50,15:12:55,00:02:05;15:42:30,15:43:30,00:01:00;16:25:30,16:27:30,00:02:00");
The strings represent the start, end and duration of down times.
(start)14:26:12,(end)14:27:19,(duration)00:01:07
I read the values in, then add them to a list of DependencyDownTime objects which hold the Long values startTime, endTime and duration.
jArray.forEach (dependency ->{
String downTimeValues = knownDowntimesMap.get(dependency);
final String[] downtime = downTimeValues.split (";");
for (final String str : downtime) {
final DependencyDownTime depDownTime = new DependencyDownTime ();
final String[] strings = str.split (",");
if (strings.length == 3) {
final DateFormat dateFormat = new SimpleDateFormat ("HH:mm:ss");
try {
depDownTime.setStartTime(dateFormat.parse (strings[0]).getTime ());
depDownTime.setEndTime (dateFormat.parse (strings[1]).getTime ());
depDownTime.setDuration (dateFormat.parse (strings[2]).getTime ());
downTimes.add (depDownTime);
} catch (final ParseException e) {
//logger.warn (e.getMessage (), e);
}
} else {
//logger.warn ("");
}
}
I then perform simple arithmetic on the values, which calculates the total down time for each component.
// sort the list by start time
Collections.sort(downTimes, Comparator.comparing (DependencyDownTime::getStartTime));
int i = 1;
Long duration = 0L;
for(DependencyDownTime dts: downTimes){
Long curStart = dts.getStartTime ();
Long curEnd = dts.getEndTime();
Long nextStart = downTimes.get(i).getStartTime ();
Long nextEnd = downTimes.get(i).getEndTime ();
if(duration == 0){
duration = dts.getDuration();
}
if(curStart.equals(nextStart) && curEnd < nextEnd){
duration += (nextEnd - curEnd);
}
else if(nextStart > curEnd){
duration += downTimes.get(i).getDuration();
}
else if( curStart < nextStart && curEnd > nextStart){
duration += (nextEnd - curEnd);
}
else if(curEnd == nextStart){
duration += downTimes.get(i).getDuration();
}
i++;
if(i == downTimes.size ()){
componentDTimeMap.put (application, duration);
return;
}
The expected values should be something like 1970-01-01T 00:14:35 .000+0100, a matter of minutes. The actual result is usually extremely high off by a matter of hours in the difference 1969-12-31T 15:13:35 .000+0100
I have 2 questions.
Am I parsing the values correctly?
If my calculations are a little off when adding and subtracting the long values. When I convert the values back to Date format will there be a drastic difference in the expected value?
As explained in your other question, don't mistake those 2 different concepts:
a time of the day: it represents a specific point of a day, such as 10 AM or 14:45:50
a duration: it represents an amount of time, such as "1 hour and 10 minutes" or "2 years, 3 months and 4 days". The duration doesn't tell you when it starts or ends ("1 hour and 10 minutes" relative to what?), it's not attached to a chronology, it doesn't correspond to a specific point in the timeline. It's just the amount of time, by itself.
In your input, you have:
(start)14:26:12,(end)14:27:19,(duration)00:01:07
The start and end represents times of the day, and the duration represents the amount of time. SimpleDateFormat is designed to work with dates and times of the day, but not with durations. Treating the duration as a time of the day might work, but it's a hack as explained in this answer.
Another problem is that when SimpleDateFormat parses only a time, it defaults the day to January 1st 1970 at the JVM default timezone, leading to all the strange results you see. Unfortunately there's no way to avoid that, as java.util.Date works with full timestamps. A better alternative is to use the new date/time API.
As in your other question you're using Java 8, I'm assuming you can also use it here (but if you're using Java <= 7, you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. The only difference is the package names (in Java 8 is java.time and in ThreeTen Backport (or Android's ThreeTenABP) is org.threeten.bp), but the classes and methods names are the same).
As you're working only with times, there's no need to consider date fields (day/month/year), we can use a LocalTime instead. You can parse the strings directly, because they are in ISO861 compliant format:
LocalTime start = LocalTime.parse("14:26:12");
LocalTime end = LocalTime.parse("14:27:19");
Unfortunately there are no built-in parsers for a duration, so you'll have to parse it manually:
// parse the duration manually
String[] parts = "00:01:07".split(":");
Duration d = Duration
// get hours
.ofHours(Long.parseLong(parts[0]))
// plus minutes
.plusMinutes(Long.parseLong(parts[1]))
// plus seconds
.plusSeconds(Long.parseLong(parts[2]));
Another alternative is to remove the durations from your input (or ignore them) and calculate it using the start and end:
Duration d = Duration.between(start, end);
Both will give you a duration of 1 minute and 7 seconds.
My suggestion is to change the DependencyDownTime to store start and end as LocalTime objects, and the duration as a Duration object. With this, your algorithm would be like this:
Duration total = Duration.ZERO;
for (...) {
LocalTime curStart = ...
LocalTime curEnd = ...
LocalTime nextStart = ...
LocalTime nextEnd = ...
if (total.toMillis() == 0) {
duration = dts.getDuration();
}
if (curStart.equals(nextStart) && curEnd.isBefore(nextEnd)) {
total = total.plus(Duration.between(curEnd, nextEnd));
} else if (nextStart.isAfter(curEnd)) {
total = total.plus(downTimes.get(i).getDuration());
} else if (curStart.isBefore(nextStart) && curEnd.isAfter(nextStart)) {
total = total.plus(Duration.between(curEnd, nextEnd));
} else if (curEnd.equals(nextStart)) {
total = total.plus(downTimes.get(i).getDuration());
}
i++;
if (i == downTimes.size()) {
// assuming you want the duration as a total of milliseconds
componentDTimeMap.put(application, total.toMillis());
return;
}
}
You can either store the Duration object, or the respective value of milliseconds. Don't try to transform it to a Date, because a date is not designed nor supposed to work with durations. You can adapt this code to format a duration if you want (unfortunately there are no native formatters for durations).
Limitations
The code above assumes that all start and end times are in the same day. But if you have start at 23:50 and end at 00:10, should the duration be 20 minutes?
If that's the case, it's a little bit trickier, because LocalTime is not aware of the date (so it considers 23:50 > 00:10 and the duration between them is "minus 23 hours and 40 minutes").
In this case, you could do a trick and assume the dates are all at the current date, but when start is greater than end, it means that end time is in the next day:
LocalTime start = LocalTime.parse("23:50");
LocalTime end = LocalTime.parse("00:10");
// calculate duration
Duration d;
if (start.isAfter(end)) {
// start is after end, it means end is in the next day
// current date
LocalDate now = LocalDate.now();
// start is at the current day
LocalDateTime startDt = now.atTime(start);
// end is at the next day
LocalDateTime endDt = now.plusDays(1).atTime(end);
d = Duration.between(startDt, endDt);
} else {
// both start and end are in the same day
// just calculate the duration in the usual way
d = Duration.between(start, end);
}
In the code above, the result will be a Duration of 20 minutes.
Don't format dates as durations
Here are some examples of why SimpleDateFormat and Date aren't good to handle durations of time.
Suppose I have a duration of 10 seconds. If I try to transform it to a java.util.Date using the value 10 to a date (AKA treating a duration as a date):
// a 10 second duration (10000 milliseconds), treated as a date
Date date = new Date(10 * 1000);
System.out.println(date);
This will get a date that corresponds to "10000 milliseconds after unix epoch (1970-01-01T00:00Z)", which is 1970-01-01T00:00:10Z. But when I print the date object, the toString() method is implicity called (as explained here). And this method converts this millis value to the JVM default timezone.
In the JVM I'm using, the default timezone is America/Sao_Paulo, so the code above outputs:
Wed Dec 31 21:00:10 BRT 1969
Which is not what is expected: the UTC instant 1970-01-01T00:00:10Z corresponds to December 31st 1969 at 9 PM in São Paulo timezone.
This happens because I'm erroneously treating the duration as a date (and the output will be different, depending on the default timezone configured in the JVM).
A java.util.Date can't (must not) be used to work with durations. Actually, now that we have better API's, it should be avoided whenever possible. There are too many problems and design issues with this, just don't use it if you can.
SimpleDateFormat also won't work properly if you handle the durations as dates. In this code:
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
Date d = dateFormat.parse("10:00:00");
The input has only time fields (hour, minute and second), so SimpleDateFormat sets the date to January 1st 1970 at the JVM default timezone. If I System.out.println this date, the result will be:
Thu Jan 01 10:00:00 BRT 1970
That's January 1st 1970 at 10 AM in São Paulo timezone, which in UTC is equivalent to 1970-01-01T13:00:00Z - so d.getTime() returns 46800000.
If I change the JVM default timezone to Europe/London, it will create a date that corresponds to January 1st 1970 at 10 AM in London (or UTC 1970-01-01T09:00:00Z) - and d.getTime() now returns 32400000 (because 10 AM in London and 10 AM in São Paulo happened at different instants).
SimpleDateFormat isn't the right tool to work with durations - it isn't even the best tool to work with dates, actually.

Android : Compare two dates with different time zones [duplicate]

I have 2 date object in the database that represent the company's working hours.
I only need the hours but since I have to save date. it appears like this:
Date companyWorkStartHour;
Date companyWorkEndHour;
start hours: 12-12-2001-13:00:00
finish hours: 12-12-2001-18:00:00
I have the timezone of the company and of the user. (my server may be in another timezone).
TimeZone userTimeZone;
TimeZone companyTimeZone;
I need to check if the user's current time (considering his timezone) is within the company working hours (considering the company's time zone).
How can I do it? I am struggling for over a week with Java calendar and with no success!
The java.util.Date class is a container that holds a number of milliseconds since 1 January 1970, 00:00:00 UTC. Note that class Date doesn't know anyting about timezones. Use class Calendar if you need to work with timezones. (edit 19-Jan-2017: if you are using Java 8, use the new date and time API in package java.time).
Class Date is not really suited for holding an hour number (for example 13:00 or 18:00) without a date. It's simply not made for that purpose, so if you try to use it like that, as you seem to be doing, you'll run into a number of problems and your solution won't be elegant.
If you forget about using class Date to store the working hours and just use integers, this will be much simpler:
Date userDate = ...;
TimeZone userTimeZone = ...;
int companyWorkStartHour = 13;
int companyWorkEndHour = 18;
Calendar cal = Calendar.getInstance();
cal.setTime(userDate);
cal.setTimeZone(userTimeZone);
int hour = cal.get(Calendar.HOUR_OF_DAY);
boolean withinCompanyHours = (hour >= companyWorkStartHour && hour < companyWorkEndHour);
If you also want to take minutes (not just hours) into account, you could do something like this:
int companyWorkStart = 1300;
int companyWorkEnd = 1830;
int time = cal.get(Calendar.HOUR_OF_DAY) * 100 + cal.get(Calendar.MINUTE);
boolean withinCompanyHours = (time >= companyWorkStart && time < companyWorkEnd);
Try something like this:
Calendar companyWorkStart = new GregorianCalendar(companyTimeZone);
companyWorkStart.setTime(companyWorkStartHour);
Calendar companyWorkEnd = new GregorianCalendar(companyTimeZone);
companyWorkEnd.setTime(companyWorkEndHour);
Calendar user = new GregorianCalendar(userTimeZone);
user.setTime(userTime);
if(user.compareTo(companyWorkStart)>=0 && user.compareTo(companyWorkEnd)<=0) {
...
}
I haven't tried the Joda library. This code should work.
public boolean checkUserTimeZoneOverLaps(TimeZone companyTimeZone,
TimeZone userTimeZone, Date companyWorkStartHour,
Date companyWorkEndHour, Date userCurrentDate) {
Calendar userCurrentTime = Calendar.getInstance(userTimeZone);
userCurrentTime.setTime(userCurrentDate);
int year = userCurrentTime.get(Calendar.YEAR);
int month = userCurrentTime.get(Calendar.MONTH);
int day = userCurrentTime.get(Calendar.DAY_OF_MONTH);
Calendar startTime = Calendar.getInstance(companyTimeZone);
startTime.setTime(companyWorkStartHour);
startTime.set(Calendar.YEAR, year);
startTime.set(Calendar.MONTH, month);
startTime.set(Calendar.DAY_OF_MONTH, day);
Calendar endTime = Calendar.getInstance(companyTimeZone);
endTime.setTime(companyWorkEndHour);
endTime.set(Calendar.YEAR, year);
endTime.set(Calendar.MONTH, month);
endTime.set(Calendar.DAY_OF_MONTH, day);
if (userCurrentTime.after(startTime) && userCurrentTime.before(endTime)) {
return true;
}
return false;
}
EDIT
Updated the code to reflect Bruno's comments. Shouldn't be taking the dates of the company work timings.
Hey I am not sure how you would do this using the Java calendar but I would highly recommend using the Joda Time package. It's a much simpler system to use and it gives you direct methods to extracts all subcomponents of data and time and even just to create simple time objects without the date involved. Then I imagine it would be a matter of comparing the 2 timezone differences and subtracting the difference from the JodaTime object.

Categories

Resources