Search code examples
androidunix-timestampandroid-date

Get unix timestamp exactly 3 years from now


Using Android and Java 8, how can I get unix timestamps back in time?

E.g.

  • Exactly 3 years back from now
  • Exactly 2 months back from now
  • Exactly 1 day back from now
  • etc

I know I can get current timestamp using System.currentTimeMillis() / 1000L (you could also use Instant.now().getEpochSecond() from the new java.time, but this requires Android API > 25). Now I need to get offset and substract it. I could use TimeUnit.Days.toSeconds(), but if I want to substract years, it does not have YEAR unit and I don't want to mess with leap years myself.

Is there a simple way to do this?


Solution

  • Try this for getting timestamp using Calender....

    For After 2 month.

        Calendar date= Calendar.getInstance();
        date.add(Calendar.MONTH, 2);//instead of 2 use -2 value in your case
        date.getTimeInMillis();
    

    For after one day.

        Calendar date= Calendar.getInstance();
        date.add(Calendar.DAY_OF_MONTH, 1);//instead of 1 use -1 value in your case
        date.getTimeInMillis();
    

    For after 3 years.

        Calendar date= Calendar.getInstance();
        date.add(Calendar.YEAR, 3);//instead of 3 use -3 value in your case
        date.getTimeInMillis();
    

    Note:- Use Negative value for back dates.

    Hope it solve your problems.