1

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

Mailerdaimon
  • 6,003
  • 3
  • 35
  • 46
Mr T
  • 1,409
  • 1
  • 17
  • 24

1 Answers1

0

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.

Scary Wombat
  • 44,617
  • 6
  • 35
  • 64