This question already has an answer here:
Closed 12 years ago.
Possible Duplicate:
warning message/pop out for date/time
I have a form where a user need to enter date and time (2 different fields) and the time cannot be in future. It can either be current time or time in past only to 12 hours before. So I want to add a warning message when the time is older than 12 hours. How will be the calculation of this in Java. Please help me out!
If you want Java this should work. JODA is good, but it is another lib dependency.
` import java.util.Calendar;
import junit.framework.TestCase;
import static java.lang.System.out;
public class DateCheck extends TestCase {
public void testCheckBefore(){
//Gets the current time
Calendar c = Calendar.getInstance();
//Let's make it 13:00 just to make the example simple.
c.set(Calendar.HOUR_OF_DAY, 13);
out.println(c.getTime());
Calendar old = Calendar.getInstance();
old.set(Calendar.HOUR_OF_DAY, 0);
if(old.after(c)) {
throw new IllegalArgumentException("You entered a date in the future");
}
assertTrue(olderThanTwelveHours(c, old));
// Let's change to 5 in the morning.
old.set(Calendar.HOUR_OF_DAY, 5);
assertFalse(olderThanTwelveHours(c, old));
}
private boolean olderThanTwelveHours(Calendar c, Calendar old) {
long startTime= c.getTimeInMillis();
long oldTime = old.getTimeInMillis();
long timeDiff = startTime - oldTime;
if(timeDiff > (12 * 60 * 60 * 1000)) {
out.println("You're too late");
return true;
}
return false;
}
}`
You are basically wanting to calculate the hours difference between 2 dates. You can easily do that using JodaTime hoursBetween method.
Related
This question already has answers here:
Calculating the difference between two Java date instances
(45 answers)
Closed 12 months ago.
So I'm having some issues in trying to do this, I already tried with this code:
thatDay.set(Calendar.DAY_OF_MONTH,25);
thatDay.set(Calendar.MONTH,7); // 0-11 so 1 less
thatDay.set(Calendar.YEAR, 1985);
Calendar today = Calendar.getInstance();
long diff = today.getTimeInMillis() - thatDay.getTimeInMillis(); //result in millis
And I kinda know why this is not what I want because, the thing that I need is taking the first date that I insert in database, and I want that to be like (CURRENTDATE - TXTDATE == DAYS THAT LEFT)
Maybe try this:
public long daysBetween(Calendar startDate, Calendar endDate) {
return TimeUnit.MILLISECONDS.toDays(Math.abs(endDate.getTimeInMillis() - startDate.getTimeInMillis()));
}
This question already has answers here:
Get first Monday after certain date?
(5 answers)
Closed 6 years ago.
Hello at first i would like to note that i have found several posts with the same question here, but NONE of them worked for me. i am creating alarm clock application for android and the last thing i need is: get the date of the nearest certain day in week.
I have found several algorithms here and i will also copy one here :
import java.util.Calendar;
public class NextWednesday {
public static Calendar nextDayOfWeek(int dow) {
Calendar date = Calendar.getInstance();
int diff = dow - date.get(Calendar.DAY_OF_WEEK);
if (!(diff > 0)) {
diff += 7;
}
date.add(Calendar.DAY_OF_MONTH, diff);
return date;
}
public static void main(String[] args) {
System.out.printf(
"%ta, %<tb %<te, %<tY",
nextDayOfWeek(Calendar.WEDNESDAY) // this can contain any of the 7 days in week
);
}
}
Today is tuesday in my country
If i put wednesday in the function it returns me the wednesday that is in the next week, but thats not correct.
This algorithm automatically looks at the following week no matter if its just monday and theres whole week before you, it jumps to the next week and does its job but thats not correct, i need to implement the same behaviour but it must start from today.
Example: Today is Monday, i am looking for wednesday
Correct output: Date of wednesday in this week.
Uncorrect output: Date of wednesday in the next week.
I hope its clear enough.
Okay, algorithm works correctly, i made a simple mistake, i was passing wrong day to the function, i passed the current day, not the one that was chosen by the user
If you wish to keep it simple.
public Date getNextDate(int dayOfWeek) {
Calendar c = Calendar.getInstance();
for ( int i = 0; i < 7; i++ ) {
if ( c.get(Calendar.DAY_OF_WEEK) == dayOfWeek ) {
return c.getTime();
} else {
c.add(Calendar.DAY_OF_WEEK, 1);
}
}
return c.getTime();
}
This question already has answers here:
How to calculate "time ago" in Java?
(33 answers)
Closed 7 years ago.
I want to display how long ago something happened. For example
24 minutes ago //discard seconds
3 hours ago //discard minutes
5 days ago // discard hours
3 weeks ago // discard days
All I have is a long timestamp and so I am free to use java.util.Date or jodatime or whatever other Time android uses. I am having such a hard time getting it right. I try to use jodatime with minus but I can't quite get the right answer yet.
One approach is for me to do the whole thing myself: first subtract my timestamp from now and then do some arithmetics. But I would rather avoid that route if possible.
Android provides the utility class DateUtils for all such requirements. If I've understood your requirement correctly, you need to use the DateUtils#getRelativeTimeSpanString() utility method.
From the docs for
CharSequence getRelativeTimeSpanString (long time, long now, long minResolution)
Returns a string describing 'time' as a time relative to 'now'. Time spans in the past are formatted like "42 minutes ago". Time spans in the future are formatted like "In 42 minutes".
You'll be passing your timestamp as time and System.currentTimeMillis() as now. The minResolution specifies the minimum timespan to report.
For example, a time 3 seconds in the past will be reported as "0 minutes ago" if this is set to MINUTE_IN_MILLIS. Pass one of 0, MINUTE_IN_MILLIS, HOUR_IN_MILLIS, DAY_IN_MILLIS, WEEK_IN_MILLIS
You can use the following code :
public class TimeAgo {
public static final List<Long> times = Arrays.asList(
TimeUnit.DAYS.toMillis(365),
TimeUnit.DAYS.toMillis(30),
TimeUnit.DAYS.toMillis(1),
TimeUnit.HOURS.toMillis(1),
TimeUnit.MINUTES.toMillis(1),
TimeUnit.SECONDS.toMillis(1) );
public static final List<String> timesString = Arrays.asList("year","month","day","hour","minute","second");
public static String toDuration(long duration) {
StringBuffer res = new StringBuffer();
for(int i=0;i< Lists.times.size(); i++) {
Long current = Lists.times.get(i);
long temp = duration/current;
if(temp>0) {
res.append(temp).append(" ").append( Lists.timesString.get(i) ).append(temp > 1 ? "s" : "").append(" ago");
break;
}
}
if("".equals(res.toString()))
return "0 second ago";
else
return res.toString();
}
}
Just call the toDuration() method with your long timestamp as parameter.
You can also use DateUtils.getRelativeTimeSpanString() . You can read the documentation here Date Utils
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
i want learn remaining time from current time to 18.30
My code is not working:
long currentTime = System.currentTimeMillis();
long endTime = 18:30;
long remaining = endTime - currentTime;
long hours = remaining / 3600000;
long mins = remaining / 60000 % 60;
long seconds = remaining / 1000 % 60;
String remainingText = String.format("%02d:%02d:%02d", hours,mins,seconds);
long endBidTime = ();
As you know, this causes a compiler error. From the comments, you seem to want to set this to 18:30 on the current day. One solution is to use the Date object. You will first need to create a Date object and set its time to 18:30. See the javadocs for the Date class for details about how to do this. You will also need to use Date.currentTimeMillis() to get the correct value for endBidTime.
You have another problem in your code:
String remainingText = "%02d:%02d:%02d".format(hours,mins,seconds);
This is incorrect and probably gives other compiler errors. Note that the format() method is static. Even though Java allows us to call static method with an instance variable, it is strongly discouraged. Instead, you should use the class name. Also, the format string is the first parameter that format() expects. This means you should do the following:
String remainingText = String.format("%02d:%02d:%02d", hours,mins,seconds);
currentTimeMillis() returns the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC. See here.
If you want to find the remaining time left till today 18:30. You have to first find the time in milliseconds at today 18:30 (then find the difference), here is my code:
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import static java.util.concurrent.TimeUnit.*;
public class timetill1830 {
public static void main(String[] args) {
int hr = 18, min = 30, sec = 0;
Calendar calendar = Calendar.getInstance();
//Now set the time for today 18:30
Calendar cal = new GregorianCalendar(calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH), hr, min, sec);
System.out.println(cal.getTimeInMillis());
System.out.println(System.currentTimeMillis());
// Now Print time left till 18:30
System.out.println("Time in millsec. till 18:30 = "
+ (cal.getTimeInMillis() - System.currentTimeMillis()));
formattedTimeLeft(cal.getTimeInMillis() - System.currentTimeMillis());
}
private static void formattedTimeLeft(long millis) {
int hrs = (int) (MILLISECONDS.toHours(millis) % 24);
int min = (int) (MILLISECONDS.toMinutes(millis) % 60);
int sec = (int) (MILLISECONDS.toSeconds(millis) % 60);
//int mls = (int) (millis % 1000);
System.out.println("Time left "+hrs+" hours "+min+" minutes "+sec+" seconds");
}
}
This question already has answers here:
Calculate Difference between two times in Android
(7 answers)
Closed 9 years ago.
I have two times, a start and a stop time, in the format of 05:00 (HH:MM). I need the difference between the two times.Suppose if start time is 05:00 and end time is 15:20, then how do I calculate the time difference between two which will be 10 Hours 20 minutes. Should I convert them into datetime object and use the milliseconds to get the time difference or is there any better approach to do this?
Use Joda Time. You want the LocalTime type to represent your start and stop times, then create a Period between them.
I don't know whether there's a cut-down version of Joda Time available for Android (it may be a little big otherwise, if your app is otherwise small) but it will make things much simpler than using the plain JDK libraries. You can do that, of course - converting both into milliseconds, finding the difference and then doing the arithmetic. It would just be relatively painful :(
Sample code:
import org.joda.time.*;
public class Test {
public static void main(String args[]) {
LocalTime start = new LocalTime(5, 0);
LocalTime end = new LocalTime(15, 20);
Period period = new Period(start, end, PeriodType.time());
System.out.println(period.getHours()); // 10
System.out.println(period.getMinutes()); // 20
}
}
And just using JDK classes:
import java.util.*;
import java.util.concurrent.*;
import java.text.*;
public class Test {
public static void main(String args[]) throws ParseException {
DateFormat format = new SimpleDateFormat("HH:mm", Locale.US);
format.setTimeZone(TimeZone.getTimeZone("UTC"));
Date start = format.parse("05:00");
Date end = format.parse("15:20");
long difference = end.getTime() - start.getTime();
long hours = TimeUnit.MILLISECONDS.toHours(difference);
long minutes = TimeUnit.MILLISECONDS.toMinutes(difference) % 60;
System.out.println("Hours: " + hours);
System.out.println("Minutes: " + minutes);
}
}
Note that this assumes that end is after start - you'd need to work out the desired results for negative times.