Skip to content Skip to sidebar Skip to footer

How To Send Date Formatted With Z And T To An Api Using Retrofit?

I have the following example path to my API - base_url/path/{country}/path/path?from=2020-03-01T00:00:00Z&to=2020-03-02T00:00:00Z So I need to pass 2 Date objects using the Z a

Solution 1:

Instant.toString() from java.time

Your format with T and Z is ISO 8601. You may want to consult the link at the bottom. The classes of java.time, the modern Java date and time API, produce ISO 8601 from their toString methods. Use the Instant class. For a brief demonstration in Java:

    Instant i = Instant.now();
    System.out.println(i);

Example output:

2020-11-18T09:31:33.613965Z

If the Instant falls on midnight in UTC, as yours do, the output will be like:

2020-11-18T00:00:00Z

The presence of decimals on the seconds in the first case probably is no issue for your API since the fraction is optional according to the ISO 8601 standard. Should you want to get rid of it, it’s easiest to truncate the Instant:

    Instant instantToPrint = i.truncatedTo(ChronoUnit.SECONDS);
    System.out.println(instantToPrint);

2020-11-18T09:31:33Z

How can I make the instant object always return T00:00:00Z as this is what my API requires?

Edit: Given that you have already got an instant that falls on the desired day in UTC, just truncate to whole days:

InstantinstantToPrint= i.truncatedTo(ChronoUnit.DAYS);

2020-11-18T00:00:00Z

The question is, though, where your date comes from. Using java.time a day in the calendar would be represented by a LocalDate, so we’d need to convert.

LocalDatefromDate= LocalDate.of(2020, Month.MARCH, 1);
    InstantfromDateTimeUtc= fromDate.atStartOfDay(ZoneOffset.UTC).toInstant();
    System.out.println(fromDateTimeUtc);

2020-03-01T00:00:00Z

  1. How can I send the formatted date into my query without it being gibrished out?

I believe that a colon in a URL needs to be URL encoded (except the colon after the protocol, the one in https://). So it should become %3A. The rest of the string from Instant should be clear to read.

Links

Post a Comment for "How To Send Date Formatted With Z And T To An Api Using Retrofit?"