How to calculate remaining days? - java

private long calculateRemainingDays() {
final Calendar c = Calendar.getInstance();
c.set(2015, 7, 23);
final Calendar today = Calendar.getInstance();
final long millis = c.getTimeInMillis()
- today.getTimeInMillis();
// Convert to days
final long days = millis / 86400000;
return days;
}
I need to add a function in my android application. I want a remaining days from current day to 2015/9/30. When the date is change to next day, the remaining days will decrease. I would like to say like that:
7 days remaining... 6/5/4/etc... Please help me to get correct remaining days. Sorry for my poor english. Thanks!

Use Calender.JULY instead of 7 in the parameters for the set() method.
7 = August.
6 = July.
As it starts with January as 0. It's better to use the static instance variables like Calender.JANUARY.
But as you want to calculate till 2015/9/30, you should set the value as
c.set(2015, Calender.SEPTEMBER, 09);
The rest of the code seems ok. It will return the correct number of days.

Try this :-
final long millis = c.getTimeInMillis()
- today.getTimeInMillis();
System.out.println ("Days: " + TimeUnit.DAYS.convert(millis , TimeUnit.MILLISECONDS));

if you don't mind using joda.time
you can do something of this form:
final Calendar c = Calendar.getInstance();
c.set(2015, Calender.SEPTEMBER, 30);
Date endDate = c.getTime();
Instant startInstant = new Instant(new Date());
Instant endInstant = new Instant(endDate);
Days days = Days.daysBetween(startInstant, endInstant);

Related

Converting difference between 2 dates to days in java 7 [duplicate]

This question already has answers here:
Calculating days between two dates with Java
(16 answers)
Closed 3 years ago.
I want to compare 2 dates in java and need to convert the difference between the 2 dates to days
//Setting up date
Calendar cal = Calendar.getInstance();
cal.set(2019, 5, 16);
Date d = cal.getTime();
Output would be something like this : Sun Jun 16 11:04:57 UTC 2019
//Getting the current date instance
Calendar cal1 = Calendar.getInstance();
Date d1 = cal1.getTime();
Output would be something like this : Mon Jul 08 11:04:57 UTC 2019
Need to get the difference between d & d1 in days.
Thanks in advance for taking your time to provide solution
Here, you just have to do simple math.
Calendar start = Calendar.getInstance();
Calendar end = Calendar.getInstance();
start.set(2010, 7, 23);
end.set(2010, 8, 26);
Date startDate = start.getTime();
Date endDate = end.getTime();
long startTime = startDate.getTime();
long endTime = endDate.getTime();
long diffTime = endTime - startTime;
long diffDays = diffTime / (1000 * 60 * 60 * 24);
DateFormat dateFormat = DateFormat.getDateInstance();
System.out.println("The difference between "+
dateFormat.format(startDate)+" and "+
dateFormat.format(endDate)+" is "+
diffDays+" days.");
This will not work when crossing daylight savings time (or leap seconds) and might as well not give the expected results when using different times of day. You can modify it like this:
start.add(Calendar.DAY_OF_MONTH, (int)diffDays);
while (start.before(end)) {
start.add(Calendar.DAY_OF_MONTH, 1);
diffDays++;
}
while (start.after(end)) {
start.add(Calendar.DAY_OF_MONTH, -1);
diffDays--;
}
Hope this helps. Good luck.
Simplest way:
public static long getDifferenceDays(Date d, Date d1) {
long diff = d1.getTime() - d.getTime();
return TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
}

Calculating days between two dates wrong output

There are a lot of replicate questions on this matter, I've looked through most of them and got to make my code, but it didn't work.
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Calendar date1 = Calendar.getInstance();
Calendar date2 = Calendar.getInstance();
String targetDate = "18/05/2015";
date2.setTime(formatter.parse(targetDate));
long diff = date2.getTimeInMillis() - date1.getTimeInMillis();
long daysPassed = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
System.out.println("Today is : "+formatter.format(date1.getTime()));
System.out.println("Target date is : "+targetDate);
System.out.println("Difference of days between them is : "+daysPassed);
With the output being :
//Today is : 17/05/2015
//Target date is : 18/05/2015
//Difference of days between them is : 0
It works but with a day less, I could just add +1, but it gives 0 if is the same day too so there's that...
I should say It's for a uni project and I can't use external libraries or something that hasn't been taught yet.
It also gives an annoying parse exception error that keeps going all over the code
If you output the timeInMillis of date1 and date2, you'll get 2 long values, for example:
1431964800000
1431916207715
and the diff is 48592285
This value can be explained as:
48592285 milliseconds
48592285/1000 = 48592.285 seconds
48592285/1000/60 = 809.87 minutes
48592285/1000/60/60 = 13.50 hours
48592285/1000/60/60/24 = 0.56 days
That's the reason why you got 0 between 2 dates you specified.

Java - Calculate Time from a timestamp of External Device with Different Epoch

So I'm kinda new to the Calendar/Time/Date stuff in Java but I've read a lot about them on the net.
Here is what I have to do:
I have an external device which sends an Avl Data Packet to my Communication Server and I'm on the parsing process of the Data part.
Somewhere in the Data Packet the device sends a timestamp of 32 bits which I have to parse/translate into the time the Record of the point from the GPS was saved.
The timestamp gives me seconds from 2007.01.01 00:00 UTC
Now here is a sample code that I felt that was the closest one I tried of the rest of the experiments..
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss.SSS");
long now = (long)(TimeStampSeconds.longValue() * 1000);
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.set(2007, 0, 1);
calendar.setTimeInMillis(now);
System.out.println(now + " = " + formatter.format(calendar.getTime()));
After that I found out that the calendar.set doesnt make a new epoch and so the .setTimeInMills doesnt work.Though I get some crazy results like:
Binary Timestamp is : 0000101011000001010110001111011100001111
SECONDS: 46193506063
46193506063000 = 25/10/3433 04:27:43.000
Shouldn't I just be missing just the 37 years between 1970 and 2007??
I want to find a way of finding the time from the seconds I get from the device but they have epoch 1/1/2007 and java has epoch 1/1/1970..
EDIT: What I want is to have time:1/1/2007 PLUS the timestamp's time. Hope I clarified the question a bit..
Someone any ideas??
Thx in Advance
It seems what you want to do is just to add your now value to the Calendar. This is easily done:
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss.SSS");
long now = (long)(TimeStampSeconds.longValue() * 1000);
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.set(2007, 0, 1);
calendar.setTimeInMillis(calendar.getTimeInMillis() + now);
System.out.println(now + " = " + formatter.format(calendar.getTime()));
EDIT
Something is weird regarding what your now variable holds. 46193506063 seconds corresponds to 1464.786468258 years according to this time converter.
Assuming you read the input in a timestamp long variable, I'd do something like:
Calendar theirEpoch = Calendar.getInstance();
theirEpoch.set(2007, 0, 1);
Calendar myEpoch = Calendar.getInstance();
myEpoch.set(1970, 0, 1);
long difference = myEpoch.getTimeInMillis() - theirEpoch.getTimeInMillis();
Calendar result = Calendar.getInstance();
result.setTimeInMillis(timestamp + difference);
I didn't test it, but it should give you the idea. Note also that I didn't take time zones into account.
This is the correct way to do what you want:
Calendar cal = Calendar.getInstance();
cal.set(2007, 1, 1, 0 ,0 ,0);
cal.set(Calendar.MILLISECOND, 0);
cal.add(Calendar.MILLISECOND, theirEpoch);
If their epoch is in seconds, change the last MILISECOND to SECOND.
The easiest thing to do is to use the roll() method of Calendar after setting the time in milliseconds:
calendar.roll(Calendar.YEAR, 37) --> just adds 37 years to your date ;-)
But I think your input data is wrong : if you take the number of seconds that have past since 01/01/2007 until now , it should be about 200 million and not 40 billion like in your example ...

Converting running pace

I'm trying to convert a running pace that I get in the format of a String (say : "5:00" for a 5 min/mile). (I am converting min/mile to min/km).
So here's what I'm doing :
String milePace = "05:00";
DateFormat sdf = new SimpleDateFormat("mm:ss");
Date date = sdf.parse(milePace);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
long mileTime = cal.getTimeInMillis();
long kmPace = Math.round(mileTime * 0.623712);
cal.setTimeInMillis(kmPace);
This unfortunately makes sense to me, but does not work.
0.623712 would be the converting unit and does work (as long as I am concerned).
When I check the value of mileTime I get 18240000. As far I can see, this is the issue as this value should be 240000 (which would be 4mins * 60 secs * 1000)
Is there an issue with the code or is there something from the cal function that would give me that extra 18000000 miliseconds?
Thanks in advance!
getTimeInMillis() returns the number of milliseconds since 1970 UTC. It will be affected by the time zone of your parser, and what date the parser decides to use for your input.
I would suggest that you use Joda Time and parse the value as a Period instead.
Sample code:
import org.joda.time.*;
import org.joda.time.format.*;
import java.util.*;
public class Test {
public static void main(String[] args) {
String text = "05:00";
PeriodFormatter formatter = new PeriodFormatterBuilder()
.minimumPrintedDigits(2)
.appendMinutes()
.appendSeparator(":")
.appendSeconds()
.toFormatter();
Period milePeriod = formatter.parsePeriod(text);
long mileMillis = milePeriod.toStandardDuration().getMillis();
long kmMillis = Math.round(mileMillis * 0.623712);
PeriodType minutesSeconds = PeriodType.time()
.withMillisRemoved()
.withHoursRemoved();
Period kmPeriod = new Period(kmMillis, minutesSeconds);
System.out.println(formatter.print(kmPeriod)); // Prints 03:07
}
}
The problem is your
Calendar.getInstance(); change this to
Calendar cal = new GregorianCalendar();
cal.set(<Calendar Constants); Reference
long miletime = cal.getTimeInMillis();
If you know that your time will stay between 0s and 59 mins inclusive, with a granularity of 1s, you could do it like this:
s = new java.text.SimpleDateFormat ("s");
m = new java.text.SimpleDateFormat ("m");
int secs = Integer.parseInt (s.format (sdf.parse ("05:00")));
int mins = Integer.parseInt (m.format (sdf.parse ("05:00")));
Adding hours might not be necessary - or do you measure something that slow?

What is the equivalent of getTime(), which is a method in Date, in joda.time.LocalDate?

I was doing a simple calculation to get the difference between two dates. If I was using a Date class I can do like this:
Date d1 = new GregorianCalendar(2000, 11, 31, 23, 59).getTime();
/** Today's date */
Date today = new Date();
// Get msec from each, and subtract.
long diff = today.getTime() - d1.getTime();
System.out.println("The 21st century (up to " + today + ") is "
+ (diff / (1000 * 60 * 60 * 24)) + " days old.");
}
But I couldn't find a method like getTime() in Local date. Is there any way so I can easily get what I am trying to achieve?
I even tried to change my LocalDate object to a temporary date object like this:
LocalDate date=new LocalDate();
Date d=date.toDate();
but the method toDate() isnt working . i.e it says it is not recognized method.(so compile time error) but from what I can see it is in the Documentation
Thank you for your time and of course happy Thanksgiving.
Days.daysBetween() is the answer.
LocalDate now = new LocalDate();
LocalDate past = now.minusDays(300);
int days = Days.daysBetween(past,now).getDays();
Never convert a LocalDate to a Java Date (two completey different beasts) if you are just dealing with dates. A Jodatime Localdate is a true "Calendar date", i.e. , a tuple of {day,month,year} (together with a Gregorian calendar specification), and has nothing to do with "physical time", with seconds, hours, etc. If you need to do dates arithmetic, stick with Localdate and you'll never need to worry about stupid bugs (timezones, DST, etc) which could arise if you dates arithmetic using java Dates.
Try something like this:
LocalDate date = new LocalDate();
Date utilDate = date.toDateTimeAtStartOfDay( timeZone ).toDate( );
or refer to this post
How to convert Joda LocalDate to java.util.Date?
I tested this sample code to find out the difference in days, you can find the difference as per your needs.
Please see http://joda-time.sourceforge.net/key_period.html
LocalDate currentDate = new LocalDate();
LocalDate previousDate = currentDate.minusDays(1);
System.out.println(currentDate);
System.out.println(previousDate);
Period periodDifference = new Period(currentDate, previousDate, PeriodType.days());
System.out.println(periodDifference);
private long diff(Calendar c1, Calendar c2) {
long d1 = c1.getTimeInMillis();
long d2 = c2.getTimeInMillis();
return ((d2 - d1) / (60*60*24*1000));
}
Have not found any equivalents for LocalDate as they are not exact.
But there are several equivalents for LocalDateTime:
LocalDateTime localDateTime = LocalDateTime.now();
long longValue = ZonedDateTime.of(localDateTime, ZoneId.systemDefault()).toInstant().toEpochMilli();
or
long longValue = localDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
or
long longValue = localDateTime.toInstant(OffsetDateTime.now().getOffset()).toEpochMilli();
or
long longValue = Timestamp.valueOf(localDateTime).getTime();

Categories