0

Say I have a url:

https://example/dateParam/

and I have a date value (ZULU format) entered by the user such as:

2016-07-20 13:10:04 +0300.

I want the result to be a properly encoded URL:

https://example/dateParam/2016-07-20%2013%3A10%3A04%20%2B0300

When I tried to do:

String dateParam = "2016-07-20 13:10:04 +0300";
String encodedParam = URLEncoder.encode(dateParam, "UTF-8");
System.out.println(encodedParam);

I get the following result:

2016-07-20+13%3A10%3A04+%2B0300

For the spaces I need %20 insteadof +. What's the best way to achieve this? I tried URLEncoder and creating URI/URL objects but none of them come out quite right.

Nick20
  • 1
  • 1
  • 2
  • How is the result you have not quite right? because the "+" is not being encoded? – Acapulco Sep 06 '18 at 16:59
  • As an aside, I don’t think there’s such a thing as a Zulu format, at least I haven’t heard about it. There’s a “Zulu time zone” with an offset of +00:00 (different from your +03:00). – Ole V.V. Sep 07 '18 at 08:57

1 Answers1

1

I suggest simplifying the problem to use a standard format like 20180906T223329Z.

Parse your input string as OffsetDateTime. Search Stack Overflow, as this has been covered many times already.

Adjust the offset-from-UTC to zero, to UTC itself.

OffsetDateTime odtUtc = odt.withOffsetSameInstant( ZoneOffSet.UTC ) ; 

Then create text in standard ISO 8601 format. The “basic” versions of these formats minimize the use of delimiters. The T separates the years-months-days from the hours-minutes-seconds. The Z on the end means UTC, and is pronounced “Zulu”. Example:

20180906T223329Z

Use DateTimeFormatter class to generate a String.

DateTimeFormatter f = DateTimeFormatterofPattern( "uuuuMMdd'T'HHmmssX" ) ;
String output = odtUtc.format( f ) ;

Lastly, run that output through your URL encoder.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154