How to get the time of the day in milliseconds? - java

I want to get the time of a day in milliseconds, I do not this day to have any specific date, just a time. I made something, thought it worked, but then went debugging and concluded that it doesn't work how I want it to.
I want to use this to check if the current time is between both my specified startTime and endTime.
long startTime = settings.getLong("startTime", 0);
long endTime = settings.getLong("endTime", 0);
if ((currentTime.getMillis() >= startTime)
&& (currentTime.getMillis() <= endTime)) {
//Do stuff here
}
How I am setting the time of the propeties startTime and endTime:
Calendar startTime = Calendar.getInstance();
startTime.set(Calendar.HOUR_OF_DAY, 16);
startTime.set(Calendar.MINUTE, 00);
editor.putLong("startTime",
startTime.getTimeInMillis());
Calendar endTime = Calendar.getInstance();
endTime.set(Calendar.HOUR_OF_DAY, 16);
endTime.set(Calendar.MINUTE, 00);
endTime.add(Calendar.HOUR_OF_DAY, 11);
editor.putLong("endTime",
endTime.getTimeInMillis());
editor.commit();
However this will mean that both startTimeand endTime will have this a specific date attached to it.
I hope I explained it well, any help is appreciated!

Avoid Milliseconds
No need to mess with milliseconds for your purpose. Using milliseconds for date-time is confusing and error-prone.
What you need is a decent date-time library rather than the notoriously troublesome bundled java.util.Date & .Calendar classes.
Joda-Time
If you are certain you want to ignore dates and ignore time zones, here's some example code using the LocalTime class offered by the third-party free-of-cost Joda-Time library.
LocalTime start = new LocalTime( 10, 0, 0 );
LocalTime stop = new LocalTime( 14, 30, 0 );
LocalTime target = LocalTime.now();
boolean isNowInSpan = !( ( target.isBefore( target ) ) | ( target.isAfter( stop ) ) );
Adjust that last line according to your business logic needs. You might want:
The beginning and ending are inclusive
The beginning and ending are exclusive
"Half-Open" where the beginning is inclusive and the ending is exclusive(usually best for date-time work)
Dump to console…
System.out.println( "start: " + start );
System.out.println( "stop: " + stop );
System.out.println( "target: " + target );
System.out.println( "isNowInSpan: " + isNowInSpan );
When run…
start: 10:00:00.000
stop: 14:30:00.000
target: 23:49:37.779
isNowInSpan: false
Another Example
Time-of-day-only is not usually the right way to go. When new to date-time work, a naïve programmer may at first think that time-only simplifies things. On the contrary, this example shows how spinning around the clock creates complications. Using date+time+timeZone is usually the best approach in the long run.
LocalTime now = LocalTime.now();
LocalTime start = new LocalTime( 13, 0, 0, 0 );
LocalTime stop = start.plusHours( 11 );
System.out.println( "now: " + now );
System.out.println( "start: " + start );
System.out.println( "stop: " + stop );
if ( now.isAfter( start ) ) {
System.out.println( "After start" );
}
if ( now.isBefore( stop ) ) {
System.out.println( "Before stop" );
}
When run…
now: 14:00:32.496
start: 13:00:00.000
stop: 00:00:00.000
After start
java.time
Java 8 brings the new java.time package, inspired by Joda-Time, defined by JSR 310.
In java.time, you will find a LocalTime class similar to the one in Joda-Time.

A new approach with Java 8 onward.
int millisecondsOfDay = LocalTime.now().get(ChronoField.MILLI_OF_DAY);
Reference: https://o7planning.org/13669/java-localtime#a64448233

Take a look at the Java 8 Time API.
http://download.java.net/jdk8/docs/api/java/time/LocalTime.html#toNanoOfDay--

Time without Date is meaning less. In Java timestamp it's using the Unix UTC and the timestamp start 0 on 01/01/1970. So, you startTime/endTime.getTimeInMillis() tell you the time different from UTC. Which mean your midnight is your base and your endTime.getTimeInMillis() will be the offset.
Calendar cal = Calendar.getInstance();
// set to mid-night
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
long midnight = cal.getTimeInMillis();
cal.set(Calendar.HOUR_OF_DAY, 16);
cal.set(Calendar.MINUTE, 00);
long startTime = cal.getTimeInMillis();
editor.putLong("startTime", (startTime - midnight));
cal.add(Calendar.HOUR_OF_DAY, 11);
long endTime = cal.getTimeInMillis();
editor.putLong("endTime", (endTime - midnight));
editor.commit();

java.time.LocalTime
I recommend that you use java.time, the modern Java date and time API, for your time work. Use a LocalTime object for time of day (it’s what it’s for).
LocalTime time = LocalTime.of(16, 0);
System.out.println(time);
Output:
16:00
If you cannot store a LocalTime object in your settings, convert to a string for human readability (a great advantage in debugging and support cases):
String timeString = time.toString();
LocalTime parsedBack = LocalTime.parse(timeString);
System.out.println(parsedBack);
16:00
To answer the question as asked, in case you need to, converting to milliseconds is straightforward (when you know how):
int milliOfDay = time.get(ChronoField.MILLI_OF_DAY);
System.out.println(milliOfDay);
57600000
The milliseconds too can be converted back to a LocalTime object:
LocalTime recreatedLocalTime
= LocalTime.MIN.with(ChronoField.MILLI_OF_DAY, milliOfDay);
System.out.println(recreatedLocalTime);
16:00
Link
Oracle tutorial: Date Time explaining how to use java.time.

In case what you need is to get how many milliseconds since the start of this day and you have now in milliseconds you can get the milliseconds you want as simple as this
val nowMilliSeconds = System.currentTimeMillis() % 86400000
Where 86400000 is the number of milliseconds in a day so you will just get the remainder

Related

How to return milliseconds from beginning of day from Calendar

I want to be able to bypass this code (getTimeInMillis() in Calendar class) and simply return the zero hour, minutes, and seconds from a specific date. Time is not set because it was built as a "Date" only now. So right now my code is always hitting this and giving me an "offset." This is even after doing below:
this.getEventDate().set(Calendar.HOUR_OF_DAY, 0);
I want to return milliseconds as long. Right now it uses Calendar.getTimeInMillis() which calculates a time as its not originally on the date object.
Is there a method out there to handle this?
public static long millisSinceStartOfToday() {
Calendar date = new GregorianCalendar();
// reset hour, minutes, seconds and millis
date.set(Calendar.HOUR_OF_DAY, 0);
date.set(Calendar.MINUTE, 0);
date.set(Calendar.SECOND, 0);
date.set(Calendar.MILLISECOND, 0);
return (new Date().getTime() - date.getTime().getTime());
}
Your Question could use a rewrite for clarity. But I’ll take a guess at what you are asking.
Avoid legacy date-time classes
You are using terrible date-time classes that were years ago supplanted by the modern java.time classes defined in JSR 310.
First moment of the day
You seem to be asking to determine the first moment of the day.
Understand that some dates in some time zones do not start at 00:00:00. So let java.time determine the first moment.
Here is an example. In Iran, the day of “Spring Ahead” in Daylight Saving Time starts at the stroke of midnight. The clock jumps to 1 AM. So the hour of 00:00:00 does not exist.
ZoneId z = ZoneId.of( "Asia/Tehran" ) ;
LocalDate ld = LocalDate.of( 2022 , Month.MARCH, 22 ) ;
ZonedDateTime zdt = ld.atStartOfDay( z ) ;
See this code run live at IdeOne.com.
2022-03-22T01:00+04:30[Asia/Tehran]
Count of milliseconds
And you apparently want to get a count of milliseconds from the epoch reference of first moment of 1970 as seen in UTC, an offset of zero hours-minutes-seconds.
Instant instant = zdt.toInstant() ; // Adjust from time zone to UTC by extracting an `Instant`.
long millis = instant.toEpochMilli() ;
1647894600000
If you want to get the number of milliseconds from a specified time to 00:00:00 of the day, the following code may help you
final long now = System.currentTimeMillis();
final long DAY_MILLIS = 1000 * 60 * 60 * 24;
//`now - (now % DAY_MILLIS)` will get the mill second at 08:00
long dayStart = now - (now % DAY_MILLIS) - DAY_MILLIS / 3;
long millisSinceStartOfToday = now - dayStart;
//in other word
//millisSinceStartOfToday = (now % DAY_MILLIS) + DAY_MILLIS / 3;

Calculate endTime using startTime and testDuration

I have the test start time (say 9:05:30) and total duration (say 5000 seconds) that a test should run.How to calculate the end time from start time and end time?
If you're using something like Instant, ZonedDateTime or LocalDateTime from the Java 8 time API, you can use plusSeconds:
Instant startTime = ...
Instant endTime = startTime.plusSeconds(5000);
If you're using Date (oh, the horrors...), you can simply use getTime:
Date startTime = ...
Date endTime = new Date(startTime.getTime() + TimeUnit.SECONDS.toMillis(5000));
In javascipt you can do
console.time('testSomeCall');
//code here
console.timeEnd('testSomeCall');
in other languages usually you get the time or timestamp before your test and then after and do end - init, like this in this for java
long timeInit = System.currentTimeMillis();
//some code here
long timeEnd = System.currentTimeMillis();
System.out.println("Ttotal time: " + (timeEnd - timeInit));
String myTime = "9:05:20";
// before calculation
Date tempStartTime = new SimpleDateFormat("HH:mm:ss").parse(myTime);
int hours = tempStartTime.getHours();
int minutes = tempStartTime.getMinutes();
int seconds = tempStartTime.getSeconds();
int elapsedSeconds = 5000;
// add seconds
int totalSeconds = seconds + elapsedSeconds;
// after calculation
Date tempEndTime = new SimpleDateFormat("HH:mm:ss").parse(hours + ":" + minutes + ":" + totalSeconds);
hours = tempEndTime.getHours();
minutes = tempEndTime.getMinutes();
seconds = tempEndTime.getSeconds();
System.out.println(hours + ":" + minutes + ":" + seconds);
// Output is 10:28:40
How can 09:05:5020 be parsed as Date?
the value is successfully parsed as the 5020th seconds, simply rolling over to next minute after each 60 seconds to accommodate the Out-Of-Bounds value. If you want to prevent this, call setLenient(false); on a DateFormat object before parsing (leniency is true by default).
The Answer by Andy Turner is correct about using java.time rather than the old date-time classes. Here's more specific detail.
java.time
The java.time framework is built into Java 8 and later. These classes supplant the old troublesome date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.
Instant
If just programmatically getting 5,000 seconds later from now, use the Instant object as shown in Turner’s Answer. An Instant is a moment on the timeline in UTC with a resolution up to nanoseconds.
Instant later = Instant.now().plusSeconds( 5_000 );
LocalTime
The LocalTime class represents a time-of-day without a date and without a time zone. So this works only for generic 24-hour days, not realistic days with time zones that have anomalies such as Daylight Saving Time (DST).
LocalTime lt = LocalTime.parse( "09:05:30" );
LocalTime later = lt.plusSeconds( 5_000 );
If hitting midnight, the result will roll-over into the early hours of the day starting with hour 00, then 01, and so on.
ZonedDateTime
If you want a realistic value that respects DST and so on, use ZonedDateTime.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
LocalDate tomorrow = LocalDate.now( zoneId ).plusDays( 1 );
LocalTime lt = LocalTime.parse( "09:05:30" );
ZonedDateTime tomorrowAround9Am = ZonedDateTime.of( tomorrow , lt , zoneId 0;
ZonedDateTime later = tomorrowAround9Am.plusSeconds( 5_000 );

How to compare "now" and a future time

I need to compare the time a local file was downloaded with a time in the future/past to see if the file needs to be re-downloaded to update it. I can get the time the local file was last downloaded with :
long timeSinceCreateFile = myFile.lastModified();
What I need is to check timeSinceCreateFile with a time that is the NEXT Friday at 21:30hs and if the current time: System.currentTimeMillis()
is in the future to this then re-download the file.
I've read heaps on Calendar, Time, Date, Joda-Time etc. but have not been able to figure out how to get a moment in time as a specific Day, Hour, Minuet, etc. that is RELATIVE to timeSinceCreateFile
Edit
I need to know the time in milliseconds between when a file was downloaded (or last modified) long timeSinceCreateFile = myFile.lastModified(); and the FOLLOWING Friday at 21:30hs (as in the Friday at 21:30hrs AFTER timeSinceCreateFile)
I can then compare the "FOLLOWING FRIDAY AT 21:30hrs" milliseconds to the current time 'System.currentTimeMillis()` and if one is greater than the other re-download the file.
Hope this clarified my question, if not let me know because I really need help with this.
Thanks.
Your temporal condition "next Friday at 21:30" is hard to realize in standard Java-library using java.util.Calendar and java.util.Date.
In Joda-Time it also requires a non-trivial workaround (again with loop).
In Java-8 (new time library JSR-310 in package java.time) an acceptable solution using specialized methods in TemporalAdjusters is possible, but since you operate on Android, this is not the way to go.
Instead here an alternative solution in my library Time4J which does not need any error-prone loops or complex conditions:
import static net.time4j.PlainDate.DAY_OF_WEEK;
import static net.time4j.Weekday.FRIDAY;
File myFile = new File("");
long timeSinceCreateFile = myFile.lastModified();
// conversion to global timestamp in Time4J-format
Moment fileTSP = TemporalTypes.MILLIS_SINCE_UNIX.transform(timeSinceCreateFile);
// what ever you need (or just TZID timezone = Timezone.ofSystem().getID();)
TZID timezone = AMERICA.MONTREAL;
// "next friday" is a local time condition => convert to local timestamp
PlainTimestamp localTSP = fileTSP.toZonalTimestamp(timezone);
PlainTime walltime2130 = PlainTime.of(21, 30);
// move to next time 21:30 (possibly on next day) and then to next or same Friday
localTSP =
localTSP.with(PlainTime.COMPONENT.setToNext(walltime2130))
.with(DAY_OF_WEEK.setToNextOrSame(FRIDAY));
// convert current time to local timestamp and compare at 21:30
boolean downloadNeeded = SystemClock.inZonalView(timezone).now().isAfter(localTSP);
GregorianCalendar ? set the date to your year, month, day, 21:30, set day of week to friday. Use getTime to get a long millisecs. This will give you a UNIX time for some friday 21:30 close to your date. Keep adding or removing the number of milliseconds in a week until the time minus your file time is in the range [0 number of milliseconds in a week]. Warning with month, it's 0 based.
public static void main(String[] args){
long fileCreateTime = new Date().getTime();
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTime(new Date(fileCreateTime));
calendar.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
calendar.set(Calendar.HOUR_OF_DAY, 21);
calendar.set(Calendar.MINUTE, 30);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
long MILLISECS_IN_A_WEEK = 7*24*60*60*1000;
long calendarMillisecs = calendar.getTime().getTime();
while(calendarMillisecs<fileCreateTime){
calendarMillisecs += MILLISECS_IN_A_WEEK;
}
while(calendarMillisecs>fileCreateTime+MILLISECS_IN_A_WEEK){
calendarMillisecs -= MILLISECS_IN_A_WEEK;
}
System.out.println(new Date(calendarMillisecs));
}
Ugly, but will work.
Avoid java.util.Date & .Calendar
Avoid java.util.Date and .Calendar because they are notoriously troublesome, flawed, and confusing. Use either Joda-Time or the new java.time package in Java 8.
Joda-Time
In Joda-Time 2.4.
DateTimeZone timeZone = DateTimeZone.forID( "America/Montreal" );
DateTime start = DateTime.now( timeZone );
// DateTime start = new DateTime( fileLastModifiedMillis, timeZone );
DateTime dateTime = start;
while ( dateTime.getDayOfWeek() != DateTimeConstants.FRIDAY ) {
dateTime = dateTime.plusDays( 1 );
}
To compare…
boolean isLate = oneDateTime.isAfter( someOtherDateTime );

Converting minutes since midnight to 24-hour time

I have minutes since midnight.
Eg 3Am is represented as = 180 (found using 3*60)
Now I need to convert it into 24 hour time format HH24 :mm = 03:00
How can we use simple date formatter/calender for this?
I would use maths, forcing the date time library to do this won't be any simpler (as it expects milli-seconds and time zone)
int mins = 180;
String hhmm = String.format("%02d:%02d", mins / 60, mins % 60);
To do much the same thing with Calendar (which will handle daylight savings you can do)
int mins = 180;
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, mins/60);
cal.set(Calendar.MINUTE, mins % 60);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
String hhmm = sdf.format(cal.getTime());
System.out.println(hhmm);
prints
03:00
However on the days when daylight savings changes you could get 02:00 or 04:00
The answer by Peter Lawrey is correct, as per usual.
Joda-Time
My added value is to give an example with an alternative library, Joda-Time, as the java.util.Date & .Calendar classes are notoriously troublesome and should be avoided.
LocalTime
Both Joda-Time and the new java.time package in Java 8 (inspired by Joda-Time) offer a LocalTime class to represent a time-only without any date or time zone. Sounds like this applies to your needs.
Just be very sure that you do not need more than LocalTime. If this data is meant to the number of minutes since midnight in Paris, and you might mix in other data that represents date-times in New York or Auckland, then you should be using the DateTime class instead of LocalTime. Naïve programmers who think/hope that ignoring time zone makes things simpler are headed for big trouble.
Example Code
Some example code in Joda-Time 2.4.
// Input
int minutes = 180;
int millisecondsSinceAnyMidnight = ( minutes * 60 * 1000 );
LocalTime localTime = LocalTime.fromMillisOfDay( millisecondsSinceAnyMidnight );
// Output
String outputDefault = localTime.toString();
DateTimeFormatter formatter = DateTimeFormat.forPattern( "HH:mm" );
String outputHHMM = formatter.print( localTime );
// Dump to console.
System.out.println( "outputDefault: " + outputDefault );
System.out.println( "outputHHMM: " + outputHHMM );
When run.
outputDefault: 03:00:00.000
outputHHMM: 03:00

Get the week start and end date given a current date and week start

If possible I would prefer a joda or non-joda solution for the scenario below
Lets say if my week starts on 02/05/2012 and the given current date is 02/22/2011. I need to calculate the week start and end date for the given current date. So my solution should have the week start as 02/19 and week ends at 02/25.
For simplicity, I have set my week start here as 02/05/2011 but it could be any day potentially and my week always has 7 days.
My existing code is below but doesnt seem to work as expected.
public Interval getWeekInterval(Date calendarStartDate, Date date)
{
Calendar sDate = Calendar.getInstance();
sDate.setTime(getMidnightDate(calendarStartDate));
Calendar eDate = Calendar.getInstance();
eDate.setTime(date);
Calendar weekStartDate = (Calendar) sDate.clone();
logger.debug("Date:" + sDate.getTime());
while (sDate.before(eDate)) {
weekStartDate = sDate;
sDate.add(Calendar.DAY_OF_WEEK_IN_MONTH, 1);
}
return new Interval(weekStartDate.getTime(), sDate.getTime());
}
Defining A Week
If you are using date-time objects, you should define a week as up to but not including the first moment of the day after the end of week. As seen in this diagram.
This approach is known as Half-Open. This approach is commonly used for working with spans of time.
The reason is because, logically, that last moment of the day before the new day is infinitely divisible as a fraction of a second. You may think that using ".999" would handle that for milliseconds, but then you'd mistaken when writing for the new java.time.* classes in Java 8 that have nanosecond resolution rather than millisecond. You may think think that using ".999999999" would handle that case, but then you’d be mistaken when handling date-time values from many databases such as Postgres that use microsecond resolution, ".999999".
In the third-party open-source Joda-Time library, this Half-Open logic is how its Interval class works. The beginning is inclusive and the ending is exclusive. This works out nicely. Similarly, calling plusWeeks(1) on a DateTime to add a week to the first moment of a day gives you the first moment of the 8th day later (see example below).
Time Zone
The question and other answers ignores the issue of time zone. If you do not specify, you'll be getting the default time zone. Usually better to specify a time zone, using a proper time zone name (not 3-letter code).
Joda-Time
Avoid the java.util.Date & Calendar classes bundled with Java. They are notoriously troublesome.
Here is some example code using Joda-Time 2.3.
CAVEAT: I have not tested of of the below code thoroughly. Just my first take, a rough draft. May well be flawed.
Standard Week (Monday-Sunday)
The Joda-Time library is built around the ISO 8601 standard. That standard defines the first day of the week as Monday, last day as Sunday.
If that meets your definition of a week, then getting the beginning and ending is easy.
UPDATE As an alternative to the discussion below, see this very clever and very simple one-liner solution by SpaceTrucker.
Simply forcing the day-of-week works because Joda-Time assumes you want:
Monday to be before (or same as) today.
Sunday to be after (or same as) today.
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
DateTime now = new DateTime( timeZone );
DateTime weekStart = now.withDayOfWeek( DateTimeConstants.MONDAY ).withTimeAtStartOfDay();
DateTime weekEnd = now.withDayOfWeek(DateTimeConstants.SUNDAY).plusDays( 1 ).withTimeAtStartOfDay();
Interval week = new Interval( weekStart, weekEnd );
Dump to console…
System.out.println( "now: " + now );
System.out.println( "weekStart: " + weekStart );
System.out.println( "weekEnd: " + weekEnd );
System.out.println( "week: " + week );
When run…
now: 2014-01-24T06:29:23.043+01:00
weekStart: 2014-01-20T00:00:00.000+01:00
weekEnd: 2014-01-27T00:00:00.000+01:00
week: 2014-01-20T00:00:00.000+01:00/2014-01-27T00:00:00.000+01:00
To see if a date-time lands inside that interval, call the contains method.
boolean weekContainsDate = week.contains( now );
Non-Standard Week
If that does not meet your definition of a week, you a twist on that code.
DateTimeZone timeZone = DateTimeZone.forID( "America/New_York" );
DateTime now = new DateTime( timeZone );
DateTime weekStart = now.withDayOfWeek( DateTimeConstants.SUNDAY ).withTimeAtStartOfDay();
if ( now.isBefore( weekStart )) {
// If we got next Sunday, go back one week to last Sunday.
weekStart = weekStart.minusWeeks( 1 );
}
DateTime weekEnd = weekStart.plusWeeks( 1 );
Interval week = new Interval( weekStart, weekEnd );
Dump to console…
System.out.println( "now: " + now );
System.out.println( "weekStart: " + weekStart );
System.out.println( "weekEnd: " + weekEnd );
System.out.println( "week: " + week );
When run…
now: 2014-01-24T00:54:27.092-05:00
weekStart: 2014-01-19T00:00:00.000-05:00
weekEnd: 2014-01-26T00:00:00.000-05:00
week: 2014-01-19T00:00:00.000-05:00/2014-01-26T00:00:00.000-05:00
First day of week depends on the country.
What makes the calculation fragile, is that one may break the year boundary, and the week number (Calendar.WEEK_OF_YEAR). The following would do:
Calendar currentDate = Calendar.getInstance(Locale.US);
int firstDayOfWeek = currentDate.getFirstDayOfWeek();
Calendar startDate = Calendar.getInstance(Locale.US);
startDate.setTime(currentDate.getTime());
//while (startDate.get(Calendar.DAY_OF_WEEK) != firstDayOfWeek) {
// startDate.add(Calendar.DATE, -1);
//}
int days = (startDate.get(Calendar.DAY_OF_WEEK) + 7 - firstDayOfWeek) % 7;
startDate.add(Calendar.DATE, -days);
Calendar endDate = Calendar.getInstance(Locale.US);
endDate.setTime(startDate.getTime());
endDate.add(Calendar.DATE, 6);
One bug in Calendar breaks your code, clone, seems to simply give the identical object, hence at the end you have identical dates. (Java 7 at least).
DateTime sDateTime = new DateTime(startDate); // My calendar start date
DateTime eDateTime = new DateTime(date); // the date for the week to be determined
Interval interval = new Interval(sDateTime, sDateTime.plusWeeks(1));
while(!interval.contains(eDateTime))
{
interval = new Interval(interval.getEnd(), interval.getEnd().plusWeeks(1));
}
return interval;
Try this (pseudo-code):
// How many days gone after reference date (a known week-start date)
daysGone = today - referenceDate;
// A new week starts after each 7 days
dayOfWeek = daysGone % 7;
// Now, we know today is which day of the week.
// We can find start & end days of this week with ease
weekStart = today - dayOfWeek;
weekEnd = weekStart + 6;
Now, we can shorten all of this to two lines:
weekStart = today - ((today - referenceDate) % 7);
weekEnd = weekStart + 6;
Note that we subtracted date values like integers to show algorithm. You have to write your java code properly.

Categories

Resources