Android Compare epoch time and today date and output the difference [duplicate] - java

This question already has answers here:
How can I convert a Unix timestamp to DateTime and vice versa?
(21 answers)
Closed 6 years ago.
I need to calculate a expiry date difference.
I will get this epoch time:
1481410800 (06-Dec-2016 (14:42))
now I want to calculate the days until the expiry date (1481410800)
Calendar now = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy (HH:mm)", Locale.getDefault());
//Expiry Date
long unixSecondsExpiry = 1481410800; //unixSeconds
Date expiryDate = new Date(unixSecondsExpiry*1000L);
long currentDate = now.get(Calendar.SECOND);
long diff = unixSecondsExpiry - currentDate;
long days = diff / (24l * 60l * 60l * 1000l);
String formattedExpiryDate = sdf.format(expiryDate);
String formattedDateNow = sdf.format(new Date());
Log.w("RUNTEST", "formattedDateNow: " + formattedDateNow);
Log.w("RUNTEST", "formattedExpiryDate: " + formattedExpiryDate);
Log.w("RUNTEST", "days: " + days);
I keep getting 17 days but it should be 5 days till expiry.
RUNTEST: formattedDateNow: 06-Dec-2016 (14:42)
RUNTEST: formattedExpiryDate: 11-Dec-2016 (07:00)
RUNTEST: days: 17

Here you are using new Date()
String formattedDateNow = sdf.format(new Date());
but the calculation is using
long currentDate = now.get(Calendar.SECOND);
Why not just use
long currentDate = new Date().getTime ();
edit
getting the SECONDS from a calendar is just getting the current seconds counter
Field number for get and set indicating the second within the minute.
E.g., at 10:04:15.250 PM the SECOND is 15.

Related

Calculate no of days between two dates in java [duplicate]

This question already has answers here:
Android/Java - Date Difference in days
(18 answers)
Closed 6 years ago.
I need to calculate number of days between two dates and I am using below code. problem is it is returning me 2 but actually it should return 3 because difference between 30 june 2016 to 27 june is 3. can you please help where it should include current date as well in difference?
public static long getNoOfDaysBtwnDates(String expiryDate) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date expDate = null;
long diff = 0;
long noOfDays = 0;
try {
expDate = formatter.parse(expiryDate);
//logger.info("Expiry Date is " + expDate);
// logger.info(formatter.format(expDate));
Date createdDate = new Date();
diff = expDate.getTime() - createdDate.getTime();
noOfDays = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
long a = TimeUnit.DAYS.toDays(noOfDays);
// logger.info("No of Day after difference are - " + TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));
System.out.println(a);
System.out.println(noOfDays);
} catch (ParseException e) {
e.printStackTrace();
}
return noOfDays;
}
expiry date is 2016-06-30 and current date is 2016-06-27
Reason is, you are not subtracting two dates with same time format.
Use Calendar class to change the time as 00:00:00 for both date and you will get exact difference in days.
Date createdDate = new Date();
Calendar time = Calendar.getInstance();
time.set(Calendar.HOUR_OF_DAY, 0);
time.set(Calendar.MINUTE, 0);
time.set(Calendar.SECOND, 0);
time.set(Calendar.MILLISECOND, 0);
createdDate = time.getTime();
More explaination in Jim Garrison' answer
Why not use LocalDate?
import java.time.LocalDate;
import static java.time.temporal.ChronoUnit.DAYS;
long diffInDays(LocalDate a, LocalDate b) {
return DAYS.between(a, b);
}
The problem is that
Date createdDate = new Date();
sets createdDate to the current instant, that is, it includes the current time as well as the date. When you parse a string using the given format, the time is initialized to 00:00:00.
Let's say you ran this at exactly 18:00 local time, you end up with
createdDate = 2016-06-27 18:00:00.000
expDate = 2016-06-30 00:00:00.000
The difference is 2 days 6 hours, not 3 days.
You should be using the newer java.time.* classes from Java 8. There is a class LocalDate that represents dates without time-of-day. It includes methods for parsing using a format, and LocalDate.now() to get the current date, as well as methods for calculating intervals between LocalDate instances.
Using the Calendar.get(Calendar.DAY_OF_MONTH) as pointed out by python:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date expDate = null;
String expiryDate ="2016-06-30";
int diff = 0;
try {
expDate = formatter.parse(expiryDate);
//logger.info("Expiry Date is " + expDate);
// logger.info(formatter.format(expDate));
Calendar cal = Calendar.getInstance();
int today = cal.get(Calendar.DAY_OF_MONTH);
cal.setTime(expDate);
diff = cal.get(Calendar.DAY_OF_MONTH)- today;
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(diff);

Java Date difference in terms of days [duplicate]

This question already has answers here:
Android/Java - Date Difference in days
(18 answers)
Closed 7 years ago.
Could anyone please help me out for calculating Date difference in terms of no of days in an efficient way?
Date nextCollectionDate = dispenseNormal.getDispensing().getNextCollectionDate();
Date currentDate = new Date();
int daysDiff = currentDate - nextCollectionDate;
//diff in msec
long diff = currentDate.getTime() - nextCollectionDate.getTime();
//diff in days
long days = diff / (24 * 60 * 60 * 1000);
You can use JodaTime which is a very useful API for these scenarios
int days = Days.daysBetween(date1, date2).getDays();
or else you can create your own method and get the difference
public long getDays(Date d1, Date d2)
{
long l = d2.getTime() - d1.getTime();
return TimeUnit.DAYS.convert(l, TimeUnit.MILLISECONDS);
}
I would suggest you to use LocalDate in Java 8:
LocalDate startDate = LocalDate.now().minusDays(1);
LocalDate endDate = LocalDate.now();
long days = Period.between(startDate, endDate).getDays();
System.out.println("No of days: " + days);
which as expected will print:
No of days: 1
You can use joda api
Below code should solve your query
Date nextCollectionDate = dispenseNormal.getDispensing().getNextCollectionDate();
Date currentDate = new Date();
Days d = Days.daysBetween(new DateTime(nextCollectionDate ), new DateTime(currentDate ))
int daysDiff = d.getDays();

Get the Difference between 2 Times [duplicate]

This question already has answers here:
Calculating the difference between two Java date instances
(45 answers)
Closed 7 years ago.
i'm trying the get the Difference between 2 dates time..
i have an arraylist, each object contains data of type Date..
My Questions are:
1) is using Calendar.getInstance().get(Calendar.MINUTE) ... etc the best way to get the current date & Time
2) should i fill manually the data in variable of Date, as follows:
Date currentDate = new Date();
currentDate.setMinutes(Calendar.getInstance().get(Calendar.MINUTE));
currentDate.setHours(Calendar.getInstance().get(Calendar.HOUR));
currentDate.setDate(Calendar.getInstance().get(Calendar.DAY_OF_MONTH));
currentDate.setMonth(Calendar.getInstance().get(Calendar.MONTH));
currentDate.setYear(Calendar.getInstance().get(Calendar.YEAR));
3) How to get the Difference between the currentDate and the an old date i have
is it like currentDate - oldDate and what about the "AM_PM" issue, should i do this function manually?
1) is using Calendar.getInstance().get(Calendar.MINUTE) ... etc the best way to get the current date
JavaDoc from java.util.Date empty constructor:
Allocates a Date object and initializes it so that it represents the
time at which it was allocated, measured to the nearest millisecond.
3) How to get the Difference between the currentDate and the an old date i have is it like currentDate - oldDate and what about the "AM_PM" issue, should i do this function manually?
Date oldDate = ...
Date currentDate = new Date();
long dt = currentDate.getTime() - oldDate.getTime();
1) To get the current date:
Date = new Date();
2) TO set manually a Date it is better to work with a Calendar.
Calendar c = new GregorianCalendar();
c.set(Calendar.MONTH, 1);
c.set(Calendar.YEAR, 2015);
// ... and so on
Date date = c.getTime();
3) to calculate the distance in ms between two dates.
Date d1 = ....;
Date d2 = ....;
long distance = d1.getTime() - d2.getTime();
Try this, variable now below is current date.
String givenDate = "03/11/2015";
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
try {
Date date = (Date)dateFormat.parseObject(givenDate);
Date now = new Date();
System.out.println(date);
System.out.println(now);
int diffInDays = (int)( (now.getTime() - date.getTime())
/ (1000 * 60 * 60 * 24) );
System.out.println(diffInDays);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You can choose any format and add time or AM/PM, see more details of SimpleDateFormat. If you dont have string dates then you can directly use date variable shown above.
Cheers !!

How to calculate difference in days between two dateboxes in GWT? [duplicate]

This question already has answers here:
Java, Calculate the number of days between two dates [duplicate]
(10 answers)
Closed 7 years ago.
I have 1 datebox (datebox1) in my GWT application, which allows users to set the date in past.
Datebox1 is set to following format (not that it probably matters):
datebox1.setFormat(new DateBox.DefaultFormat (DateTimeFormat.getFormat("EEE, MMM dd, yyyy")));
How do I programatically calculate the difference in days between the date selected in the date box and the current date.
I can't find much on the net and would appreciate a simple example.
The simplest way:
Date currentDate = new Date();
int daysBetween = CalendarUtil.getDaysBetween(myDatePicker.getValue(), currentDate);
the below code block will be useful for you
Date selectedDate = DateBox.getDatePicker().getValue();
Date currentDate= new Date();
long fromDate = selectedDate.getTime();
long toDate = currentDate.getTime();
long diffGap = toDate - fromDate;
long diffDays = diffGap / (24 * 60 * 60 * 1000);
If you know how to extract date from your textbox, you can use the following function to get the time difference between any two dates
public String getTimeDiff(Date dateOne, Date dateTwo) {
String diff = "";
long timeDiff = Math.abs(dateOne.getTime() - dateTwo.getTime());
diff = String.format("%d hour(s) %d min(s)", TimeUnit.MILLISECONDS.toHours(timeDiff),
TimeUnit.MILLISECONDS.toMinutes(timeDiff) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(timeDiff)));
return diff;
}

How do I add 2 weeks to a Date in java? [duplicate]

This question already has answers here:
Modify the week in a Calendar
(4 answers)
Closed 5 years ago.
I am getting a Date from the object at the point of instantiation, and for the sake of outputting I need to add 2 weeks to that date. I am wondering how I would go about adding to it and also whether or not my syntax is correct currently.
Current Java:
private final DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
private Date dateOfOrder;
private void setDateOfOrder()
{
//Get current date time with Date()
dateOfOrder = new Date();
}
public Date getDateOfOrder()
{
return dateOfOrder;
}
Is this syntax correct? Also, I want to make a getter that returns an estimated shipping date, which is 14 days after the date of order, I'm not sure how to add and subtract from the current date.
Use Calendar and set the current time then user the add method of the calendar
try this:
int noOfDays = 14; //i.e two weeks
Calendar calendar = Calendar.getInstance();
calendar.setTime(dateOfOrder);
calendar.add(Calendar.DAY_OF_YEAR, noOfDays);
Date date = calendar.getTime();
I will show you how we can do it in Java 8. Here you go:
public class DemoDate {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
System.out.println("Current date: " + today);
//add 2 week to the current date
LocalDate next2Week = today.plus(2, ChronoUnit.WEEKS);
System.out.println("Next week: " + next2Week);
}
}
The output:
Current date: 2016-08-15
Next week: 2016-08-29
Java 8 rocks !!
Use Calendar
Date date = ...
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.WEEK_OF_MONTH, 2);
date = c.getTime();
Try this to add two weeks.
long date = System.currentTimeMillis() + 14 * 24 * 3600 * 1000;
Date newDate = new Date(date);
if pass 14 to this addDate method it will add 14 to the current date and return
public String addDate(int days) throws Exception {
final DateFormat dateFormat1 = new SimpleDateFormat(
"yyyy/MM/dd HH:mm:ss");
Calendar c = Calendar.getInstance();
c.setTime(new Date()); // Now use today date.
c.add(Calendar.DATE, addDays); // Adding 5 days
return dateFormat1.format(c.getTime());
}
Using the Joda-Time library will be easier and will handle Daylight Saving Time, other anomalies, and time zones.
java.util.Date date = new DateTime( DateTimeZone.forID( "America/Denver" ) ).plusWeeks( 2 ).withTimeAtStartOfDay().toDate();
If you are on java 8 you can use new date time api http://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html#plusWeeks-long-
if you are on java 7 or more old version of java you should use old api http://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html#add-int-int-

Categories

Resources