3

I want my step counter to display steps from 12 am to 12 am I cant find a way to that is working. I am using Google's fitness API

here's the code:

        Calendar cal = Calendar.getInstance();
        Date today = new Date();
        cal.setTime(today);
        long endTime = cal.getTimeInMillis();
        cal.add(Calendar.MONTH, -1);
        long startTime = cal.getTimeInMillis();

        java.text.DateFormat dateFormat = DateFormat.getDateInstance();
        Log.e("History", "Range Start: " + dateFormat.format(startTime));
        Log.e("History", "Range End: " + dateFormat.format(endTime));

//Check how many steps were walked and recorded in the last 7 days
        final DataReadRequest readRequest = new DataReadRequest.Builder()
                .aggregate(DataType.TYPE_STEP_COUNT_DELTA, DataType.AGGREGATE_STEP_COUNT_DELTA)
                .bucketByTime(1, TimeUnit.DAYS)
                .setTimeRange(startTime, endTime, TimeUnit.MILLISECONDS)
                .build();

        final DataReadResult dataReadResult = Fitness.HistoryApi.readData(mGoogleApiClient, readRequest).await(1,TimeUnit.MINUTES);
Ayush Kshitij
  • 125
  • 2
  • 11
  • [This](https://stackoverflow.com/questions/6850874/how-to-create-a-java-date-object-of-midnight-today-and-midnight-tomorrow) should help. – Andrew S Nov 08 '18 at 14:08
  • 12 am to 12 am as in the 24 hours in between? Why is this subtracting a month then? Why does the comment say "last 7 days"? – M. Prokhorov Nov 08 '18 at 15:08
  • @M.Prokhorov Yes, the solution below worked for me. Previously I was retrieving last week's data but I changed my mind. – Ayush Kshitij Nov 09 '18 at 07:32
  • FYI, the terribly troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Nov 10 '18 at 06:08
  • FYI, days do not always run 12 AM to 12 AM. – Basil Bourque Nov 10 '18 at 06:44

3 Answers3

2

java.time

You are using terrible old date-time classes that were supplanted years ago by the java.time classes defined in JSR 310.

LocalDate

First, get the date of interest. If you want “today”, you must specify a time zone.

The LocalDate class represents a date-only value without time-of-day and without time zone or offset-from-UTC.

A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.

If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment during runtime(!), so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "America/Montreal" ) ;  
LocalDate today = LocalDate.now( z ) ;

If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the JVM’s current default is applied implicitly. Better to be explicit, as the default may be changed at any moment during runtime by any code in any thread of any app within the JVM.

ZoneId z = ZoneId.systemDefault() ;  // Get JVM’s current default time zone.

First moment of the day

12 am to 12 am

A day does not always run from 12 AM to 12 AM!

Never assume when a day begins or ends. A day is not always 24 hours long, it can be 23, 23.5, 25, or any other number of hours dreamed up by the politicians defining the time zone. In some zones on some dates, the day may not start at 00:00, it may start at some other time such as 01:00. Let java.time determine when a day begins and ends.

Half-Open

Generally the best approach in defining a span-of-time is the Half-Open approach. In this approach, the beginning is inclusive while the ending is exclusive. This avoids the challenge of trying to determine the exact split-second end of the day. A day starts at the first moment of one date and runs up to, but does not include, the first moment of the next date.

ZonedDateTime zdtStart = ld.atStartOfDay( z ) ;  // First moment of the day as seen in the wall-clock time used by the people of a particular region as defined arbitrarily by their politicians (a time zone).
ZonedDateTime zdtStop = ld.plusDays( 1 ).atStartOfDay( 1 ) ;  // First moment of the day of the *following* date.

Epoch reference date, & granularity

The Google API for DataReadRequest.Builder::setTimeRange takes count of some granularity since some epoch reference date. Unfortunately, nether the limit of the granularity nor the epoch reference is specified – and there are many epoch references in use.

I will take a guess at seconds being the finest granularity, and guess at 1970-01-01T00:00Z being the epoch reference. This epoch is used by the java.time classes and by the terrible old java.util.Date class.

long secondsSinceEpoch_Start = zdtStart.toEpochSecond() ;
long secondsSinceEpoch_Stop = zdtStop.toEpochSecond() ;

Make your call to the API.

            …
            .setTimeRange( 
                secondsSinceEpoch_Start , 
                secondsSinceEpoch_Stop , 
                TimeUnit.SECONDS
            )
            …

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
0
you can try like this

            Date date1 = new Date();
            SimpleDateFormat  formatter1 = new SimpleDateFormat("MMddyyyy"); 
            String format = formatter1.format(date1);
            SimpleDateFormat  formatter = new SimpleDateFormat("MMddyyyy hh:mm:ss"); 
            Calendar cal = Calendar.getInstance();
            Date today = formatter.parse(format+" 00:00:00");
            cal.setTime(today);
            long start = cal.getTimeInMillis();
            System.out.println("start time:"+start);
            Date date=formatter.parse(format+" 23:59:59");
            cal.setTime(date);
            long end = cal.getTimeInMillis();
            System.out.println("end time: "+end);

            Date tem= new Date();

            cal.setTime(tem);

            long present = cal.getTimeInMillis();

            System.out.println(present);
  • **Incorrect** on three counts. (a) Using this code, data occurring in last second of the day will never be reported. (b) A day is not always 24-hours long. (c) A day does not always start at 00:00. – Basil Bourque Nov 10 '18 at 06:40
0

If you need the start of day, you should set it as such:

Calendar cal = new GregorianCalendar();
cal.clear(Calendar.HOUR); cal.clear(Calendar.AM_PM);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
// after all this we'd have the start of day.
// works good if extracted to separate method, which is the unfortunate truth of working with  old calendar classes

// minus one milli because Fit API treats includes end of range
long end = cal.getTimeInMillis() - 1;

cal.add(Calendar.MONTH, -1);
long start = cal.getTimeInMillis();

I also may suggest to import and use Joda library for this (prefer Android-specific version). Using Joda (and java.time package once Java 8 is available on Fit, with minor change), you can write equivalent code like this:

DateTime date = LocalDate.now().toDateTimeAtStartOfDay();

long end = date.getMillis() - 1;

long start = date.minusMonths(1).getMillis();
M. Prokhorov
  • 3,894
  • 25
  • 39