Quick question:
I´m having an Interval of one day:
Interval interval = new LocalDate().toInterval(DateTimeZone.getDefault());
Suppose I want to add one day at the beginning and one day at the end.
Right now I use the methods withDurationBeforeEnd and withDurationAfterStart which don´t really fit to my use case. Am I missing something? I was looking for some API like Interval.addPeriod(Period period);
Or am I completely wrong and should use something else?
Interval newInterval = new Interval(oldInterval.getStart().minusDays(1), oldInterval.getEnd().plusDays(1));
Related
I know it may seems easy but i'm really new on Java , So i need your help.
I want to use local time (Mill Seconds) to trigger an action, for example printing "Hello world".
More specific, Print "Hello world" at "13:10:30:300" . but i don't know what specific class should i use (Data,Local Time , etc) so i can compare it to Desired Time in a while loop.
I tried this, but it's not working on milliseconds.
import java.time.format.DateTimeFormatter;
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("HH:mm:ss:ms");
LocalDateTime now = LocalDateTime.now();
LocalDateTime desire = 13:10:30.300;
while (now != desire ) {
LocalDateTime now = LocalDateTime.now();
}
System.out.println("Hello World!");
Do you have any suggestion please?
Your main problem is this: now != desire. This compares whether these objects are the same, not whether their contents are the same. To compare if the times are the same, you should use now.equals(desire).
Your second problem is that this this loop might become infinite if between 2 checks now becomes greater than desire.
Your third problem is that you are wasting CPU cycles constantly checking the time. You should calculate how many milliseconds your desired time is away and sleep until then. So something like: Thread.sleep(desireMillis - nowMillis)
I am looking to calculate the number of minutes given the time of the day.
Eg.: when input is 11:34, the output should be 11*60+34. The date doesn't matter.
I only need it down to the minutes scale. Seconds, milliseconds... don't matter.
Is there a method somewhere in Java doing this the neat way without me calculating it?
Right now, i'm using theTime.split(":"), theTime is a String holding "11:34" here, parsing the integers on each side and doing the calculation.
I saw Time but what I'm doing right now seemed more direct.
Nothing in Systems either.
There is no build in method for it. However here is a one-liner for it:
int timeInMins = Calendar.getInstance().get(Calendar.HOUR_OF_DAY) * 60 + Calendar.getInstance().get(Calendar.MINUTE);
Your approach looks good and sound, however to answer your question it would be simple to say that there is no such build in method which does that. You have to calculate it the way you are doing it right now.
Hi maybe you could use JodaTime? Below example how to get number of minutes from parsed string and from current time. In java 8 there is similar api but I haven't found exactly method like minutesOfDay()
#Test
public void learnHowManyMinutesPassedToday() {
DateTime time = DateTimeFormat.forPattern("HH:mm").parseDateTime("11:34");
System.out.println(time.getMinuteOfDay());
System.out.println(DateTime.now().getMinuteOfDay());
}
If you are looking to have input not from a String, take a look at
Java.util.Calendar.
It has Calendar.HOUR_OF_DAY and Calendar.HOUR and Calendar.MINUTE which could be your input. I'm not sure what the "neat" way of doing this would be. It is a simple calculation.
Calendar rightNow = Calendar.getInstance();
int hour = rightNow.get(Calendar.HOUR);
int min = rightNow.get(Calendar.MINUTE);
System.out.println("TimeMinutes:" + hour * 60 + min);
EDIT:
Except using split use the above.
I want to have my application execute code at a point in the future.
I want to do:
Date now = new Date();
for (Date beep : scheduledBeeps) {
if (beep.after(now))
{
Logger.i("adding beep");
m_beepTimer.postAtTime(beepNow, beep.getTime());
}
}
In the log I can see 4 beeps added, however they never fire. I'm assuming it has something to do with uptimeMillis, but I'm not sure what to do.
You will have to get the difference between now and beep.gettime() and pass it to postattime function. Since uptime is used as base, it may not be accurate if the phone goes to deep sleep.
beep.gettime - now + SystemCLock.uptimeMillis()
should be passed to postattime function
You are currently passing a very large number equivalent to current milliseconds from jan 1 1970.
You could use the Calendar class to set a certain point in time.
Calendar beepTime = Calendar.getInstance();
beepTime.set(Calendar.DAY_OF_MONTH, 2);
beepTIme.set(Calendar.HOUR_OF_DAY, 01);
beepTime.set(Calendar.MINUTE, 55);
beepTime.set(Calendar.SECOND, 00);
getInstance will set it to the current time, and you can change any variable you like, such as the ones above. For example this would create a time at 1:55 on the 2nd of the current month. You would then set this to be the time to go off with
beepTime.getTimeInMillis()
just pop that into your postAtTime method
Edit: Also I don't know enough about your problem to say for sure, but it may be better to use AlarmManager. I know that that still works even if the program is not running, whereas I don't think PostDelayed does. Feel free to correct me if I'm wrong!
I need to calculate the time passed between two dates.
The catch here is that I need to show it as YouTube does with its video comments timestamps. That is, to show it by just the largest measure.
For example,
if the time is 50 seconds ago it should say 50 seconds ago.
if the time is more than one minute it should say one minute ago/ten minutes ago etc..
if the time difference is 1 hour 30 mins it should show: an hour ago.
if the time is one and a half week than it should say one week ago.
if the time is more than a month it should say one month ago/two months ago etc...
and so on and so on..
So what is the best way to handle this?
Should I make a method with case or if statements that would return something like this? Or is there a better approach (maybe a library which already does something like it)?
Use DateUtils.getRelativeTimeSpanString(long time, long now, long minResolution). time is the start time, and now is the end time (in milliseconds). To report "seconds ago," set minResolution to zero.
Example:
String result = DateUtils.getRelativeTimeSpanString(1306767830, 1306767835, 0);
// result = "5 seconds ago"
date1.getTime() - date2.getTime()
This will return you the time in miliseconds between the 2 dates. Just convert that to what ever you want to show (e.g. hours minutes seconds)
On Android, use this: http://developer.android.com/reference/android/text/format/DateUtils.html#getRelativeTimeSpanString%28android.content.Context,%20long,%20boolean%29
Take a look at PrettyTime!
Also, everytime you want to do something date/time-related in Java, you should take a look at Joda Time. Do it now, you will thank me later.
Your need is very specific, and I don't know any lib that would solve the problem for you out of the box.
However the problem is not very complex and a small function full of "ifs" should do the trick.
Of course, a nice date library like Joda Time will help you keep your code clean. Who wants to use GregorianCalendar!?
Looks like you have a set of custom rules and the algorithm to choose a rule is based on the time in seconds between two timestamps. The easiest approach is to handle the rules in a series of if/else if statements:
private String getTimeAsString(int seconds) {
if (seconds < 60) { // rule 1
return String.format("%s seconds ago", seconds);
} else if (seconds < 3600) { // rule 2
return String.format("%s minutes ago", seconds/60);
} // ... and so on
}
Is there a better way of doing this?
boolean oneCalendarWeek = interval.getStart().plusWeeks(1).equals( interval.getEnd() );
I guess the following won't work because of the way equals is implemented...
boolean oneCalendarWeek = interval.toPeriod().equals( Weeks.ONE );
From the comments:
i really want to know if the api supports something like my second example which i think is clearer than the first
While the example using Weeks.ONE does not work (since Period.equals() first checks if the two Period instances support the same number of fields, and Weeks.ONE only supports one field), this should work instead:
boolean oneCalendarWeek = interval.toPeriod().equals( Period.weeks(1) );
Here is a code sample that tests this for an interval that starts before the start of DST and ends while in DST. However, I'm not 100% sure how this would behave if the start or end time of the Interval fell exactly on the DST boundary.