Search code examples
androidsqlitedatetimejava-timelocaldatetime

Which is best as Timestamp in Android [only using new Java.time]? LocalDateTime or Instant.now()?


Issue:

I need to save a timestamp in SQLITE Database (Android) and extract date from it. Which is the best way LocalDateTime or Instant.now()? as this Android application is being used in Saudi Arabia.

Requirement:

I must query the Timestamp column for the very first Timestamp entered in DB and extract date alone from it to compare it with the present day date to check if the day difference exceeds 30 days.

Need help with:

  1. The best of two LocalDateTime or Instant.now()
  2. How to extract the date alone from that best way. Appreciate help.

So Far done:

I have used LocalDateTime to save Timestamp but not sure how to extract date only from it.


Solution

  • Given below is all that you asked for:

    import java.time.Instant;
    import java.time.LocalDate;
    import java.time.LocalDateTime;
    import java.time.LocalTime;
    import java.time.Month;
    import java.time.ZoneId;
    import java.time.ZoneOffset;
    import java.time.ZonedDateTime;
    import java.time.temporal.ChronoUnit;
    
    public class Main {
        public static void main(String[] args) {
            // The current moment at UTC time-scale
            Instant now = Instant.now();
            System.out.println(now);
    
            // The number of milliseconds from the epoch of 1970-01-01T00:00:00Z.
            long millis = now.toEpochMilli();
            System.out.println(millis);
    
            // The number of seconds from the Java epoch of 1970-01-01T00:00:00Z.
            long seconds = now.getEpochSecond();
            System.out.println(seconds);
    
            // Zone ID of Saudi Arabia
            ZoneId zoneId = ZoneId.of("Asia/Riyadh");
    
            // Get ZonedDateTime from Instant
            ZonedDateTime zdt = now.atZone(zoneId);
            System.out.println(zdt);
    
            // Get the LocalDateTime part of this ZonedDateTime
            LocalDateTime ldt = zdt.toLocalDateTime();
            System.out.println(ldt);
    
            // Get the LocalDate part of this ZonedDateTime
            LocalDate today = zdt.toLocalDate();
            System.out.println(today);
    
            // An instant in the past
            Instant past = LocalDateTime.of(LocalDate.of(2020, Month.APRIL, 10), LocalTime.MIDNIGHT)
                    .toInstant(ZoneOffset.ofHours(3));// Zone Offset of Saudi Arabia is UTC +3
            System.out.println(past);
    
            // No. of months
            long months = ChronoUnit.MONTHS.between(past.atZone(zoneId), zdt);
            System.out.println(months);
        }
    }
    

    Output:

    2020-08-27T08:45:31.927452Z
    1598517931927
    1598517931
    2020-08-27T11:45:31.927452+03:00[Asia/Riyadh]
    2020-08-27T11:45:31.927452
    2020-08-27
    2020-04-09T21:00:00Z
    4