How to find number of days between two unix timestamps in java - java

I am using unix timestamp to store the purchase date in my application.
sample data: 1371463066
I want to do some manipulation based on the difference in number of days and current day timestamp.
for example: If the number of days between the purchase date and current date is 5 days, then send an email regarding feedback again.
how to get the difference in days between two timestamps using java?

I have not tested it but you may try to do something like this:
Date purchasedDate = new Date ();
//multiply the timestampt with 1000 as java expects the time in milliseconds
purchasedDate.setTime((long)purchasedtime*1000);
Date currentDate = new Date ();
currentDate .setTime((long)currentTime*1000);
//To calculate the days difference between two dates
int diffInDays = (int)( (currentDate.getTime() - purchasedDate.getTime())
/ (1000 * 60 * 60 * 24) )

Unix timestamp is the number of seconds since 1.1.1970. If you have 2 unix timestamps then the difference in full days is
int diff = (ts1 - ts2) / 3600 / 24

You could try with Calendars (which will also allow you to use TimeZones):
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(1371427200l * 1000l);
Calendar newCalendar = Calendar.getInstance();
newCalendar.setTimeInMillis(1371527200l * 1000l);
// prints the difference in days between newCalendar and calendar
System.out.println(newCalendar.get(Calendar.DAY_OF_YEAR) - calendar.get(Calendar.DAY_OF_YEAR));
Output:
1

Related

Get time from long value [duplicate]

This question already has answers here:
Android:Display time after adding GMT time zone
(2 answers)
Closed 4 years ago.
I am converting milliseconds to the time of the respective country time format, for example, pakistan, US etc
For example
timeinmilliseconds=1549362600000
So its respective Time formate from which I got these milliseconds is 15:30 or 3:30 in 12 hr format
When I want to convert these milliseconds back to that time
I get 10:30 (Five hrs back)
public String getTimeFromLong(long timeInMilliseconds){
String mytime="";
long minute = (timeInMilliseconds / (1000 * 60)) % 60;
long hour = (timeInMilliseconds / (1000 * 60 * 60)) % 24;
mytime = String.format("%02d:%02d", hour, minute);
return mytime;
}
If I select time 4:00
I converted to that to milliseconds (This part is OK)
And wants the time back from milliseconds but get five hours back
For example, If I select time 9:30
convert it to milliseconds and then to time
I get 4:30
You need to use your local time zone to get the time in your region, the default is being apllied which is the Greenwich Mean Time (GMT). For Pakistan use Asia/Karachi like so:
SimpleDateFormat simpleDateFormat= new SimpleDateFormat("hh:mm");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Karachi"));
Use this method to convert milliseconds into your local time
public String getTime(long time){
Calendar calendar = new GregorianCalendar();
calendar.setTimeInMillis(time);
SimpleDateFormat format = new SimpleDateFormat("hh:mm a");
Date date = new Date(time);
String kTime = format.format(date);
return kTime;
}
Using Java 8 we can do the following.
LocalDateTime dateTime =
LocalDateTime.ofInstant(Instant.ofEpochMilli(longValue), ZoneId.systemDefault());
to get date and time
Use below code to get time from long values:
public String getTimeFromLong(long timeInMilliseconds){
// Creating date format
DateFormat simple = new SimpleDateFormat("dd MMM yyyy HH:mm:ss:SSS Z");
Date result = new Date(timeInMilliseconds);
return simple.format(result);
}

Span in days between two dates misunderstanding

I have a misundertood managing dates in Java when I want to calculate the span in number of days between two dates.
Say we have two different dates:
Date 1: 1986-01-24
Date 2: 2017-04-20
Case 1: I have this snippet of code using Dates:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date dt1 = format.parse("1986-01-24");
Date dt2 = format.parse("2017-04-20");
int intSpanInDays= (int) ((dt2.getTime() - dt1.getTime()) / (1000 * 60 * 60 * 24));
System.out.println("Days between: " + intSpanInDays);
Output 1:
Days between: 11408
Case 2: Snippet of code using Calendar:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
GregorianCalendar cal1 = new GregorianCalendar();
cal1.setTime(format.parse("1986-01-24"));
cal1.set(Calendar.HOUR, 0);
cal1.set(Calendar.MINUTE, 0);
cal1.set(Calendar.SECOND, 0);
GregorianCalendar cal2 = new GregorianCalendar();
cal2.setTime(format.parse("2017-04-20"));
cal2.set(Calendar.HOUR, 0);
cal2.set(Calendar.MINUTE, 0);
cal2.set(Calendar.SECOND, 0);
long spanInMillis = cal2.getTimeInMillis() - cal1.getTimeInMillis();
GregorianCalendar cal3 = new GregorianCalendar();
cal3.setTimeInMillis(spanInMillis);
long millisInADay = 1000 * 60 * 60 * 24;
System.out.println("Days between: " + (cal3.getTimeInMillis() / millisInADay));
Output 2:
Days between: 11408
Case 3: Example using a spreadsheet in Excel:
When I use MS Excel to get this span just introducing the given dates and simply substracting, the output is this:
QUESTION
Why is Java calculation code of date missing one day? What is missing or wrong in either case 1 and 2 that does not match the result in case 3?
The spreadsheet is taking Daylight Savings into account, and your calculations are naively truncating, and given that there's one more 23-hour day in the interval than 25-hour days, the 23-hour remainder is truncated, yielding a result one day less than the correct answer.
JDK 8 largely simplifies these calculations with its new date time API. The same can be done accurately and simply using the below code :
LocalDate date1 = LocalDate.of(1986, 01, 24);
LocalDate date2 = LocalDate.of(2017, 04, 20);
System.out.println(date1.until(date2, ChronoUnit.DAYS));
This automatically takes care of any/all the DST changes, leap years etc. which is mostly missed when trying to do the calculations manually.

Java calculating time with timestamps [duplicate]

This question already has answers here:
Calculating the difference between two Java date instances
(45 answers)
Closed 7 years ago.
Im trying to calculate the time difference between 2 Timestamps, this is the code:
Calendar calendar = Calendar.getInstance();
java.util.Date now = calendar.getTime();
Timestamp currentTimestamp = new Timestamp(now.getTime());
System.out.println("Current\n"+currentTimestamp);
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date date = dateFormat.parse("28/02/2015");
Timestamp timestampBefore = new Timestamp(date.getTime());
System.out.println("Before\n"+timestampBefore);
Timestamp calculated = new Timestamp(currentTimestamp.getTime() - timestampBefore.getTime());
System.out.println("Calculated\n"+calculated);
Output:
Current
2015-02-28 12:12:40.975
Before
2015-02-28 00:00:00.0
Calculated
1970-01-01 13:12:40.975
I can understand why it returns 1970-01-01 but why does it return 13:12:40.975 ,1 hour more?
How to calculate the difference between 2 dates so the output is like this (based on this example):
Years:0, Months:0, Days:0, Hours:12, Minutes:12, Seconds:40 ?
Update: for java below 1.8 check out http://www.joda.org/joda-time/index.html
and for java 1.8 see answer.
Similar solution here: Java 8: Calculate difference between two LocalDateTime
(1) A timestamp is a point in time. If you calculate the difference between two timestamps, the result is not a timestamp (point in time), but a duration. So it is nonsense to convert the difference to a timestamp, hence it is useless to discuss the reason why the result is strange.
(2) You should probably use the new Java 8 time API (if you are able to use Java 8):
LocalTime now = LocalTime.now();
LocalTime previous = LocalTime.of(0, 0, 0, 0);
Duration duration = Duration.between(previous, now);
System.out.println(now);
System.out.println(previous);
System.out.println(duration);
Note that this just calculates the duration between two times of a day (hour-minute-second). If your want to include date information, use LocalDateTime instead:
LocalDateTime nextFirework = LocalDate.now()
.with(TemporalAdjusters.firstDayOfNextYear())
.atTime(LocalTime.MIDNIGHT);
LocalDateTime now = LocalDateTime.now();
// duration (in seconds and nanos)
Duration duration = Duration.between(now, nextFirework);
// duration in total hours
long hours = now.until(nextFirework, ChronoUnit.HOURS);
// equals to: duration.toHours();
If you want to have 'normalized' duration in years/months/days/hours/seconds, there is suprisingly no direct support. You could convert the duration to days, hours, minutes and seconds by yourself:
long d = duration.toDays();
long h = duration.toHours() - 24 * d;
long m = duration.toMinutes() - 60 * duration.toHours();
long s = duration.getSeconds() - 60 * duration.toMinutes();
System.out.println(d + "d " + h + "h " + m + "m " + s + "s ");
But note that you will have difficulties converting the days into months and years, as there is no unique number of days per month and a year can be a leap year with 366 days. For that, you can use Period, as in opposite to Duration, this class is associated with a timeline. Unfortunately, Period does only support dates, but no times:
// period in years/months/days (ignoring time information)
Period p = Period.between(now.toLocalDate(), nextFirework.toLocalDate());
System.out.println(p); // or use p.getYears(), p.getMonths(), p.getDays()
So probably you could combine both approaches - first, compute the Period from the dates and then the Duration using the times. Note that the duration can be negative, so you'll have to take care of that in case of:
Duration dur = Duration.between(start.toLocalTime(), end.toLocalTime());
LocalDate e = end.toLocalDate();
if (dur.isNegative()) {
dur = dur.plusDays(1);
e = e.minusDays(1);
}
Period per = Period.between(start.toLocalDate(), e);
System.out.println(per.toString() + ", " + dur.toString());

Get Account Expiration date from active directory

I am trying to convert Account Expires attribute of AD to date. Here is how I am trying to do it:
long adDate = Long.parseLong(adDateStr);
long milliseconds = (adDate / 10000) - DIFF_NET_JAVA_FOR_DATES;
Date date = new Date(milliseconds);
DateFormat mydate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return(mydate.format(date));
The problem is it is adding 1 day to the actual account expires day.
e.g. if the account expires date is 08/01/2106 than the code above is giving 09/01/2016.
Can anyone help me with this?
Just some guesses.
Is the value of DIFF_NET_JAVA_FOR_DATES = 11644473600000L + 24 * 60 * 60 * 1000?
The time in accountExpires and the Date is UTC time (not local).
Is this the reason?

How to subtract start time from stop time

I've the following two dates in a string format and would like to get the elapsed time for those.
Date elapsed = new Date(
new SimpleDateFormat().parse("10/17/2014, 2:19:22 PM").getTime()
- new SimpleDateFormat().parse("10/17/2014, 2:19:32 PM").getTime());
System.out.println("Elapsed Time: " + elapsed);
However, I get ...ParseException: Unparseable date: "10/17/2014, 2:19:22 PM" does anyone know why?
Note: here is how I got the date you see in parse block generated new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(time)
You have to specify format in SimpleDateFormat constructor.
Your String has format dd/MM/yyyy, hh:mm:ss a
Your logic of substraction is incorrect as it will give you the long value difference between dates and you are creating date from that value which is not valid.For that you have to get exact difference from that long value.You have to divide diff with (1000 * 60) to get minutes, (1000 * 60 * 60) to get Seconds and (1000 * 60 * 60 * 24) to get days.
SimpleDateFormat sdf= new SimpleDateFormat("dd/MM/yyyy, hh:mm:ss a");
long diff = sdf.parse("10/17/2014, 2:19:22 PM").getTime()
- sdf.parse("10/17/2014, 2:18:32 PM").getTime();
System.out.println("Difference : " + (diff / (1000d * 60 )) +" Minutes");
NOTE: 1000d is used to perform floating point arithmetic here.
However, I get ...ParseException: Unparseable date: "10/17/2014, 2:19:22 PM" does anyone know why?
Because you haven't told SimpleDateFormat what the format of the string will be. Use one of the constructor that accepts a pattern string so that it knows what to expect.

Categories