How To Send Date Formatted With Z And T To An Api Using Retrofit?
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
- 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
- Wikipedia article: ISO 8601
- Oracle tutorial: Date Time explaining how to use java.time.
- Java Specification Request (JSR) 310, where
java.time
was first described. - ThreeTen Backport project, the backport of
java.time
to Java 6 and 7 (ThreeTen for JSR-310). - Java 8+ APIs available through desugaring
- ThreeTenABP, Android edition of ThreeTen Backport
- Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
Post a Comment for "How To Send Date Formatted With Z And T To An Api Using Retrofit?"