How to check if time stamp (epoch time) is of today's or yesterday's [android]

12,157

Solution 1

Its really simple:

Calendar c=Calendar.getInstance();
c.getTimeInMillis();
String cur_day=String.format("%te %B %tY",c,c,c); // This will give date like 22 February 2012

c.setTimeInMillis(time);//set your saved timestamp
String that_day=String.format("%te %B %tY",c,c,c); //this will convert timestamp into format like 22 February 2012

//you can compare days,months,year,hours,minutes,seconds and milliseconds using above method.you can find various formats in below link

For more formats,please refer http://download.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html

Solution 2

You can use methods:

public static long diff(long time, int field) {
  long fieldTime = getFieldInMillis(field);
  Calendar cal = Calendar.getInstance();
  long now = cal.getTimeInMillis();
  return (time/fieldTime - now / fieldTime);
}

private static final long getFieldInMillis(int field) {
  // TODO cache values
  final Calendar cal = Calendar.getInstance();
  long now = cal.getTimeInMillis();
  cal.add(field, 1);
  long after = cal.getTimeInMillis();
  return after - now;
}

and use them this way:

diff(time, Calendar.DAY_OF_YEAR); // 0 - today, 1 - tomorrow, -1 - yesterday
diff(time, Calendar.WEEK_OF_YEAR); // 0 - this week, -1 - last week etc.

Solution 3

You can try to use this for detect today date:

public static boolean isDateToday(long milliSeconds) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(milliSeconds);

        Date getDate = calendar.getTime();

        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);

        Date startDate = calendar.getTime();

        return getDate.compareTo(startDate) > 0;

    }

Solution 4

i think this is the most efficient way of figuring out if two timestamps are on the same day. plus it's language-independent:

int secondsInADay   = 60*60*24;
int daysSinceEpoch1 = timestamp1/secondsInADay;
int daysSinceEpoch2 = timestamp2/secondsInADay;

if( daysSinceEpoch1 == daysSinceEpoch2 )
    ;//sameday

else if( daysSinceEpoch1 - daysSinceEpoch2 == 1 )
    ;//timestamp2 is a day before timetamp1

else if( ......

set timestamp1 to the current time if you want to compare to today

Solution 5

java.time

The legacy date-time API (java.util date-time types and their formatting type, SimpleDateFormat etc.) is outdated and error-prone. It is recommended to stop using it completely and switch to java.time, the modern date-time API*.

Solution using java.time, the modern API:

The modern date-time API is rich with intuitive concepts e.g. it provides us with the class, Instant which represents an instantaneous point on the timeline. There is a class called ZonedDateTime which represents a date-time with a time-zone in the ISO-8601 calendar system. In order to switch to a different time unit (e.g. day, hour, minute, week, month etc.), the API provides methods named as prepositions and other spoken English constructs. Learn more about the modern date-time API from Trail: Date Time.

The concepts like today, yesterday, same week etc. are bounds to a timezone e.g a moment today in London can be tomorrow in Singapore. Also, the start of the week is Locale-sensitive e.g. for Locale.France, it starts on Monday whereas for Locale.US, it starts on Sunday.

Demo:

import java.time.DayOfWeek;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.temporal.TemporalAdjusters;
import java.util.stream.Stream;

public class Main {
    public static void main(String[] args) {
        // Test
        Stream.of(
                    1621533017083L,
                    1621446617083L,
                    1621619417083L,
                    1621189684296L,
                    1621209600000L,
                    1621814400000L
        ).forEach(millis -> {
            System.out.println(millis);
            System.out.println(Instant.ofEpochMilli(millis));
            System.out.println("Today: " + isToday(millis, "Europe/London"));
            System.out.println("Yesterday: " + isYesterday(millis, "Europe/London"));
            System.out.println("In the current week: " + isInTheSameWeek(millis, "Europe/London"));
            System.out.println();
        });
    }

    static boolean isToday(long epochMillis, String timezone) {
        ZoneId zoneId = ZoneId.of(timezone);

        // The start of the day today at this timezone
        ZonedDateTime zdtStartOfDayToday = LocalDate.now().atStartOfDay(zoneId);
        long millisStartOfDayToday = zdtStartOfDayToday.toInstant().toEpochMilli();

        // The start of the next day at this timezone
        ZonedDateTime zdtStartOfDayNextDay = LocalDate.now().plusDays(1).atStartOfDay(zoneId);
        long millisStartOfDayNextDay = zdtStartOfDayNextDay.toInstant().toEpochMilli();

        return (epochMillis >= millisStartOfDayToday && epochMillis < millisStartOfDayNextDay);
    }

    static boolean isYesterday(long epochMillis, String timezone) {
        ZoneId zoneId = ZoneId.of(timezone);

        // The start of the day today at this timezone
        ZonedDateTime zdtStartOfDayToday = LocalDate.now().atStartOfDay(zoneId);
        long millisStartOfDayToday = zdtStartOfDayToday.toInstant().toEpochMilli();

        // The start of the day yesterday at this timezone
        ZonedDateTime zdtStartOfDayYesterday = LocalDate.now().minusDays(1).atStartOfDay(zoneId);
        long millisStartOfDayYesterday = zdtStartOfDayYesterday.toInstant().toEpochMilli();

        return (epochMillis >= millisStartOfDayYesterday && epochMillis < millisStartOfDayToday);
    }

    static boolean isInTheSameWeek(long epochMillis, String timezone) {
        ZoneId zoneId = ZoneId.of(timezone);

        // The start of the day today at this timezone
        ZonedDateTime zdtStartOfDayToday = LocalDate.now().atStartOfDay(zoneId);

        // The start of the week at this timezone
        ZonedDateTime zdtStartOfTheWeek = zdtStartOfDayToday.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
        long millisStartOfTheWeek = zdtStartOfTheWeek.toInstant().toEpochMilli();

        // The start of the next week at this timezone
        ZonedDateTime zdtStartOfTheNextWeek = zdtStartOfDayToday.with(TemporalAdjusters.next(DayOfWeek.MONDAY));
        long millisStartOfTheNextWeek = zdtStartOfTheNextWeek.toInstant().toEpochMilli();

        return (epochMillis >= millisStartOfTheWeek && epochMillis < millisStartOfTheNextWeek);
    }
}

Output:

1621533017083
2021-05-20T17:50:17.083Z
Today: true
Yesterday: false
In the current week: true

1621446617083
2021-05-19T17:50:17.083Z
Today: false
Yesterday: true
In the current week: true

1621619417083
2021-05-21T17:50:17.083Z
Today: false
Yesterday: false
In the current week: true

1621189684296
2021-05-16T18:28:04.296Z
Today: false
Yesterday: false
In the current week: false

1621209600000
2021-05-17T00:00:00Z
Today: false
Yesterday: false
In the current week: true

1621814400000
2021-05-24T00:00:00Z
Today: false
Yesterday: false
In the current week: false

ONLINE DEMO


* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Share:
12,157
User7723337
Author by

User7723337

C, C++, Java, Android, AngularJS, JavaScript, HTML and CSS Developer. But mostly interested in Java and Android.

Updated on August 07, 2022

Comments

  • User7723337
    User7723337 almost 2 years

    I want to convert the time stamp (epoch time) to human readable string.

    For that i am using calendar.setTimeInMillis(timeSinceEpoch) function to create the calender object and to get the date time string in human readable format.

    I am confused on, How can I find out that the time stamp (epoch time) is of today or yesterday or it is in the same week as per the system's current date and time?

    Is there any API's to achieve this in android?

    Thanks.

  • User7723337
    User7723337 over 12 years
    Actually my question is, can i test the milliseconds that i have from epoch time are of today, yesterday or they are from the same week as per the current system time.
  • Hiral Vadodaria
    Hiral Vadodaria over 12 years
    That you will have to implement by yourself.such automatic comparison are not available.
  • User7723337
    User7723337 over 12 years
    so it will be like, for comparing if it is of today then i have to get the current system time and check year, month and date then i will get to know if time stamp is of today or not.
  • Hiral Vadodaria
    Hiral Vadodaria over 12 years
    @PP.: yes..absolutely.you just need to be sure you compare it correcly and don't miss any related parameter.For.ex: checking hour should not ignore AM/PM difference.
  • sawyer seguin
    sawyer seguin over 10 years
    For a best effort solution, this is fine. If you need exact answers (to the hour or second) be aware that the timestamp includes daylight saving switch hours and leap seconds, so getFieldInMillis will not return the exact same value in these cases and the results may be off a bit. (e. g. on a day before daylight saving, it will report 23 or 25 days as 24 days, since the "next" day has 23 or 25 hours. To get exact answers, validate them by calling cal.add with the resulting "best effort" value and verify the result is accurate enough and if not correct it.
  • MSaudi
    MSaudi over 9 years
    Be careful to the previous comment.
  • Grumblesaurus
    Grumblesaurus about 9 years
    Only correction I need was to cast to an int, because timestamp is in long. Otherwise, great answer. Thank you!
  • JacksOnF1re
    JacksOnF1re about 8 years
    Besides that secondsInADay won't work, because not every day has this exact amount of time, therefore your method will result in false results at some time of the day.
  • Amir
    Amir almost 8 years
    Easier way : DateUtils.isToday()