0

I am trying to change the output date format for my google calendar code, but it cannot be used in SimpleDateFormater because it is a google api date, not the java version.

I did get it to work but eventually removed that code because it always returned null.

my app activity would display it as "(my event) on Null", where my event would update but the date always returned null.

Im not great at working with googles API and am newish to java, so any help will be appreciated!

Here is my code:

import android.os.AsyncTask;

import com.google.api.client.googleapis.extensions.android.gms.auth.GooglePlayServicesAvailabilityIOException;
import com.google.api.client.googleapis.extensions.android.gms.auth.UserRecoverableAuthIOException;
import com.google.api.client.util.DateTime;
import com.google.api.services.calendar.model.Event;
import com.google.api.services.calendar.model.Events;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * An asynchronous task that handles the Google Calendar API call.
 * Placing the API calls in their own task ensures the UI stays responsive.
 */

/**
 * Created by miguel on 5/29/15.
 */

public class ApiAsyncTask3 extends AsyncTask<Void, Void, Void> {
    private MainActivity mActivity3;

    /**
     * Constructor.
     * @param activity MainActivity that spawned this task.
     */
    ApiAsyncTask3(MainActivity activity) {
        this.mActivity3 = activity;
    }

    /**
     * Background task to call Google Calendar API.
     * @param params no parameters needed for this task.
     */
    @Override
    protected Void doInBackground(Void... params) {
        try {
            mActivity3.clearResultsText();
            mActivity3.updateResultsText(getDataFromApi());

        } catch (final GooglePlayServicesAvailabilityIOException availabilityException) {
            mActivity3.showGooglePlayServicesAvailabilityErrorDialog(
                    availabilityException.getConnectionStatusCode());

        } catch (UserRecoverableAuthIOException userRecoverableException) {
            mActivity3.startActivityForResult(
                    userRecoverableException.getIntent(),
                    BlockOrderGCalDaily.REQUEST_AUTHORIZATION);

        } catch (IOException e) {
            mActivity3.updateStatus("The following error occurred: " +
                    e.getMessage());
        }
        return null;
    }

    /**
     * Fetch a list of the next 10 events from the primary calendar.
     * @return List of Strings describing returned events.
     * @throws IOException
     */
    private List<String> getDataFromApi() throws IOException {
        // List the next 10 events from the primary calendar.
        DateTime now = new DateTime(System.currentTimeMillis());
        List<String> eventStrings = new ArrayList<String>();
        Events events = mActivity3.mService.events().list("9sfoekroead5j1sb8aduqgvog4@group.calendar.google.com")
                .setMaxResults(1)
                .setTimeMin(now)
                .setOrderBy("startTime")
                .setSingleEvents(true)
                .execute();
        List<Event> items = events.getItems();

        for (Event event : items) {
            DateTime start = event.getStart().getDateTime();
            if (start == null) {
                // All-day events don't have start times, so just use
                // the start date.
                start = event.getStart().getDate();

            }



            eventStrings.add(
                    String.format("%s on %s", event.getSummary(), start));
        }
        return eventStrings;
    }

}
Zunkey
  • 45
  • 5
  • 2
    It looks like `com.google.api.client.util.DateTime` has a [`getValue()` method](https://developers.google.com/api-client-library/java/google-http-java-client/reference/1.20.0/com/google/api/client/util/DateTime.html#getValue()) which "Returns the date/time value expressed as the number of milliseconds since the Unix epoch.", which could easily be converted to whichever date/time type you need it in; e.g., `java.util.Date`. – Mike M. Sep 30 '18 at 03:55
  • 1
    Only don’t use `Date`. That class is long outdated and poorly designed. Instead look into [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). It’s so much nicer to work with and offers all the formatting capabilities you can dream of. – Ole V.V. Sep 30 '18 at 03:58
  • Though be aware that `java.time` is not available, natively, on Android until API level 26, so you'll need to use a library for earlier versions. I'm sure @OleV.V. can link you to the relevant info. – Mike M. Sep 30 '18 at 04:02
  • 1
    Using the `getValue` method that @MikeM. linked to I believe that [this answer by Basil Bourque](https://stackoverflow.com/a/49378569/5772882) will give you the rest. – Ole V.V. Sep 30 '18 at 04:48

2 Answers2

1

Get a count of milliseconds since the epoch reference of 1970-01-01T00:00:00Z. Call com.google.api.client.util.DateTime::getValue.

long millis = myDateTime.getValue() ;

Parse those as an java.time.Instant.

Instant instant = Instant.ofEpochMilli( millis ) ;

Adjust from UTC to the time zone you care about.

ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;

Generate a string.

DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL ).withLocale( Locale.CANADA_FRENCH ) ;
String output = zdt.format( f ) ;

For earlier Android, see the ThreeTenABP project.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
0
Date javaDate = new Date(googleDate.getValue());

You can then format it however you choose.

Sheharyar
  • 73,588
  • 21
  • 168
  • 215