How to use time in calculations (half hours) - java

I want to make a program that's checking if an input is greater than 8h30m. How do I accomplish this? I thought maybe about java.util.Calendar or Date but I don't know how those things work.

Use the Duration from Java 8:
String input = "8h";
Duration duration = Duration.parse("PT" + input);
Duration compared = Duration.ofHours(8).plus(Duration.ofMinutes(30));
int compare = duration.compareTo(compared); // -1
// compare would be 0 for input="8h30m" and 1 for input="8h40m"
Edit - You can substract times as well, get the seconds for example:
Duration diff = duration.minus(compared);
int seconds = diff.getSeconds();

Try using Joda Timer
http://www.joda.org/joda-time/
You can use DateTime for that and us function isAfter for your case.

If what you want is to check if the current time is before another time, you can do this:
public Boolean foo() {
Calendar currentlyCal = Calendar.getInstance(); // This is the currently time.
Calendar calToCheck = Calendar.getInstance();
calToCheck.set(Calendar.HOUR_OF_DAY, 8);
calToCheck.set(Calendar.MINUTE, 30);
return currentlyCal.before(calToCheck); // or use after() instead of before() if it's what you want.
}
EDIT
The difference:
public void getDifference(Calendar cal1, Calendar cal2) {
long diff = cal2.getTimeInMillis() - cal.getTimeInMillis();
long seconds = diff/1000;
long hour = seconds/3600;
seconds = seconds%3600;
long minutes = seconds/60;
seconds = seconds%60;
// .. do something
}

Related

How can you check if a given time in milliseconds was yesterday?

Given a time in milliseconds, how can you check if it was yesterday?
You would first convert the millis to a Date or LocalDate and then run the comparison.
Here's a quick example:
import java.time.*;
class DateCheckSample {
public static void main(String[] args) {
// Our input date
long millis = System.currentTimeMillis();
// Convert the millis to a LocalDate
Instant instant = Instant.ofEpochMilli(millis);
LocalDate inputDate = instant.atZone(ZoneId.systemDefault()).toLocalDate();
// Grab today's date
LocalDate todaysDate = LocalDate.now();
System.out.println(millis);
// Check if date is yesterday
if (todaysDate.minusDays(1).equals(inputDate)) {
System.out.println(inputDate + " was yesterday!");
} else {
System.out.println(inputDate + " was NOT yeseterday!");
}
}
}
The Result:
2019-02-16 was NOT yesterday!
If you'd like to confirm it's working, just subtract 100000000 from millis before running.
Side Note: As pointed out in the comments on your question, 23:59 is not a millis value...
If you don't want to use Date, you can simply use the modulus operator with a bit of clever arithmetics. System#currentTimeMillis returns the amount of milliseconds that have passed since January 1, 1970, midnight (00:00).
Combining this with the number of milliseconds in a day (86,400,000), we can figure the time at which the last start of day was — which is when today began. Then we can see if the time given to us is smaller or larger than that value.
boolean isToday(long milliseconds) {
long now = System.currentTimeMillis();
long todayStart = now - (now % 86400000);
if(milliseconds >= todayStart) {
return true;
}
return false;
}
To check if a time is yesterday instead of today, we simply check if it is between the start of today and the start of yesterday.
boolean isYesterday(long milliseconds) {
long now = System.currentTimeMillis();
long todayStart = now - (now % 86400000);
long yesterdayStart = todayStart - 86400000;
if(milliseconds >= yesterdayStart && < todayStart) {
return true;
}
return false;
}
You can convert the milliseconds to Date and then compare the day with today's Date.
For reference: Convert millisecond String to Date in Java

How to add two Milliseconds in android

I want to calculate difference between two times which is calculate correctly then i have to half it so i divide it with 2 results are okay. but when i am trying to add the timdedifferencemillis to startTime its not giving me the correct result...
starttime= 05:53
endtime= 17:57
i want results 11:55
but my code giving me 06:55
please help.....
protected String transitTime2(String endtime, String starttime) {
SimpleDateFormat dt = new SimpleDateFormat("hh:mm");
Date startTime = null;
Date endTime;
long timdedifferencemillis = 0;
try {
startTime = dt.parse(starttime);
endTime = dt.parse(endtime);
long diff=startTime.getTime();
timdedifferencemillis = (endTime.getTime() - startTime.getTime())/2;
//timdedifferencemillis
} catch (ParseException e) {
e.printStackTrace();
}
long timdedifferencemillis1=startTime.getTime()+timdedifferencemillis;
int minutes = Math
.abs((int) ((timdedifferencemillis1 / (1000 * 60)) % 60));
int hours = Math
.abs((int) ((timdedifferencemillis1 / (1000 * 60 * 60)) % 24));
String hmp = String.format("%02d %02d ", hours, minutes);
return hmp;
}
The problem is probably time zone; when you parse endtime and starttime initially, by default (in the absence of an explicit time zone indicated in the format string and represented in the input), Java assumes that the times provided are relative to the local time zone of the system. Then, when you call getTime(), it returns
the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object
One solution is to tell your SimpleDateFormat object to assume that all strings it parses are in GMT, rather than in the local time zone. Try adding this line after you initialize dt, but before calling dt.parse(...):
dt.setTimeZone(TimeZone.getTimeZone("GMT"));
This is quite easy to do with the new java.time API in Java 8 or with the JODA Time library:
import java.time.Duration;
import java.time.LocalTime;
public class TimeDiff {
public static void main(String[] args) {
LocalTime start = LocalTime.parse("05:53");
LocalTime end = LocalTime.parse("17:57");
// find the duration between the start and end times
Duration duration = Duration.between(start, end);
// add half the duration to the start time to find the midpoint
LocalTime midPoint = start.plus(duration.dividedBy(2));
System.out.println(midPoint);
}
}
Output:
11:55
By using LocalTime objects, you avoid any problems with time zones.
I think the problem is the types "long" and "int" in your code ;when we divide with 2 ( long timdedifferencemillis )the result must be "double".

Comparing Just the Date (not time)

I need to compare 2 dates to a third date and ignore the time portion of all of them.
The code below generates a parse exception because the toString() method returns something like "Wed Feb 26 00:00:00 EST 2014".
Any suggestions on how I might fix this?
private boolean needToSendEmail(EmSelfCertEntity escd) throws ParseException {
boolean sendEmail = false;
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
Date justTheDate = df.parse(escd.getCurrentFCESDate().toString());
Calendar firstSent = Calendar.getInstance();
firstSent.setTime(justTheDate);
justTheDate = df.parse(new Date().toString());
Calendar firstFollowUp = Calendar.getInstance();
firstFollowUp.setTime(justTheDate);
firstFollowUp.add(Calendar.DATE, -daysToFirstFollowUpEmail);
Calendar secondFollowUp = Calendar.getInstance();
secondFollowUp.setTime(justTheDate);
secondFollowUp.add(Calendar.DATE, -daysToSecondFollowUpEmail);
if ((firstSent.before(firstFollowUp) && escd.countEmailsSent <= 1)
|| (firstSent.before(secondFollowUp) && escd.countEmailsSent <= 2)) {
sendEmail = true;
}
return sendEmail;
}
Thanks!
Why are you parsing the String when you already have the Date?
If you want to format your existing Date into the format you specified, use the format() method instead:
String justTheDate = df.format(new Date());
Then you can compare the Strings using the equals() method to check for matches.
Edit- By the way, if Java 8 is an option (it came out on Tuesday!), its new DateTime features will do exactly what you're looking for: http://docs.oracle.com/javase/tutorial/datetime/
The cause for your exception is that toString in escd.getCurrentFCESDate().toString()
delivers another format than "MM/dd/yyyy".
So make sure that either your format String in line SimpleDateFormat("MM/dd/yyyy") is correct.
Or check if you can get the year, month, and day directly from getCurrentFCESDate().
Just Use the calendar to create a date, where you take the year, months, day from the existing date but set the hours, minutes, seconds and millis to zero.
The result will be a Date object:
Something like
firstSent.set(Calendar.HOUR, 0);
firstSent.set(Calendar.MINUTE, 0);
firstSent.set(Calendar.SECOND, 0);
firstSent.set(Calendar.MILLISECOND, 0);
Then use before() and after()
The easiest approach would be to convert the dates to numbers in this format: yyyyMMdd.
And after that you can just compare the numbers.
But yes, please work with timezone adjustments before converting to numbers.
you can calculate the time in millis and substract the time with a simple / division.
This way you can compare 2 longs and check if one is bigger than another.
Take this example where we get to different dates for today (500 milliseconds from one to another) but... if you divide by 86400000 then... you get the same number.
Try this:
public static void main(String[] args) throws Exception {
Date d1= new Date();
Thread.sleep(500);
Date d2= new Date();
final int MILLISECONDS = 1000;
final int SECONDS = 60;
final int MINUTES = 60;
final int HOURS = 24;
final long MILLI_PER_DAY= MILLISECONDS*SECONDS*MINUTES*HOURS;
System.out.println(MILLI_PER_DAY);
System.out.println(d1.getTime());
System.out.println(d2.getTime());
System.out.println(d1.getTime()/MILLI_PER_DAY);
System.out.println(d2.getTime()/MILLI_PER_DAY);
}
You will see that the last 2 entries are the same:
1395338535623 --> time 1 in millis
1395338536123 --> time 2 in millis
16149 --> time 1 / 86400000
16149 --> time 2 / 86400000 --> THE SAME

how to check : dateOne < dateTwo

I need help to check following conditions related to date and time...
Calendar cal = Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
String CurrentDate= dateFormat.format(cal.getTime());
String ModifiedDate = dateTime taken from date n time picker widget ;
i have to check :
current ModifiedDate is not less than 5 minutes of current time
How to check this conditon in Android / Java..........?
Why are you formatting the date?
It's much easier to work with data in a "natural" representation rather than in a string representation. It's not clear whether your modified date has to be taken as a string, but if it does, the first thing you should do is parse it. You can then compare that with the current date and time using:
// Check if the value is later than "now"
if (date.getTime() > System.currentTimeMillis())
or
// Check if the value is later than "now + 5 minutes"
if (date.getTime() > System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(5))
It's not really clear what you mean by "current ModifiedDate is not less than 5 minutes of current time" - whether you mean that it's not less than 5 minutes after, or not less than 5 minutes earlier, or something like that - but you should be able to change the code above to handle your requirements.
If you do a lot of date/time manipulation, I'd strongly recommend the use of Joda Time, which is a much better date/time API than java.util.Date/Calendar.
To check whether the given time is before/after the current time ,
There is a Calendar instance in Android...to compare date time values.
Calendar current_time = Calendar.getInstance ();
current_time.add(Calendar.DAY_OF_YEAR, 0);
current_time.set(Calendar.HOUR_OF_DAY, hrs);
current_time.set(Calendar.MINUTE, mins );
current_time.set(Calendar.SECOND, 0);
Calendar given_time = Calendar.getInstance ();
given_time.add(Calendar.DAY_OF_YEAR, 0);
given_time.set(Calendar.HOUR_OF_DAY, hrs);
given_time.set(Calendar.MINUTE, mins );
given_time.set(Calendar.SECOND, 0);
current_time.getTime();
given_time.getTime();
boolean v = current_calendar.after(given_calendar);
// it will return true if current time is after given time
if(v){
return true;
}
public static boolean getTimeDiff(Date dateOne, Date dateTwo) {
long timeDiff = Math.abs(dateOne.getTime() - dateTwo.getTime());
int day = (int) TimeUnit.MILLISECONDS.toHours(timeDiff);
int min= (int) ( TimeUnit.MILLISECONDS.toMinutes(timeDiff) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(timeDiff)));
if(day>1)
{
return false;
}
else if(min>5)
{
return false;
}
else
{
return true;
}
}
usage:
System.out.println(getTimeDiff(new Date("01/13/2012 12:05:00"),new Date("01/12/2012 13:00:00")));

How to write a method that returns number (int) of days from provided day to the todays date?

Please help me to write a method that returns number (int) of days from a provided day to the todays date.
So let's say, I am providing into a method an int 110515 (for May 15, 2011). It should return 9 (inclusive or exclusive is not important to me).
If you can use Joda, this is super simple:
Days d = Days.daysBetween(startDate, endDate);
int days = d.getDays();
Of course you could combine these.
int days = Days.daysBetween(startDate, endDate).getDays();
Joda objects can go back and forth between the JDK's date class pretty easily.
For the first part, make a DateFormatter then parse the string based on it, like this:
DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyyMMdd");
DateTime dt = fmt.parseDateTime(strInputDateTime);
(After turning the int into a string of course.)
Should dates in the future include the current day? Meaning if today is May 24th 2011, should 110529 result in 4 or 5?
public static long numberOfDays(final long date) throws ParseException {
final Calendar compare = Calendar.getInstance();
compare.setTime(new SimpleDateFormat("yyMMdd").parse(String.valueOf(date)));
final int dstOffset = compare.get(Calendar.DST_OFFSET);
final long currentTimeMillis = System.currentTimeMillis();
final long compareTimeInMillis = compare.getTimeInMillis();
long difference = 0;
if (currentTimeMillis >= compareTimeInMillis) {
difference = currentTimeMillis - compareTimeInMillis - dstOffset;
} else {
difference = compareTimeInMillis - currentTimeMillis + dstOffset;
}
return difference / (24 * 60 * 60 * 1000);
}
Since this seems like a homework question I will help you out. You will want to use Calendar.getTimeInMillis. Then you will want to create a constant that is NUMBER_OF_MILLIS_IN_DAY . From there you subtract the initialDate from the currentDate (both time in millis) and divide by the constant.

Categories