简体   繁体   中英

How to change date format to parse into url_string?

I am using an API to retrieve taxi data via a URL link in Android (java).

I am able to successfully retrieve the data using the following format. However, the date and time 2018-07-17T18%3A49%3A00 is hardcoded and i would like it to be done dynamically using current date and time.

String URL_STRING =
                "https://api.data.gov.sg/v1/transport/taxi-availability?date_time=2018-07-17T18%3A49%3A00";

I have tried the following method but i am not able to get it dynamically. i am receiving a null response from the API server. Appreciate if you can shed some light on what i am doing wrong.

Date currentTime = Calendar.getInstance().getTime();

SimpleDateFormat formatter = new SimpleDateFormat("YYYY-MM-DD'T'HH:MM:SS");

String URL_STRING =
                "https://api.data.gov.sg/v1/transport/taxi-availability?date_time=" + formatter.format(currentTime);

One possible solution can be to encode your URL using native method:

String encodedDate = URLEncoder.encode(myString, "utf-8");

Another problem is that your formatting pattern is wrong, referring to the official documentation , YYYY should be yyyy and your minute time should be mm instead of MM ( MM is month ). also seconds are lowercase , since uppercase are milliseconds.

Using the method above, your code will look like

Date currentTime = Calendar.getInstance().getTime();

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
String mDate = formatter.format(currentTime);

String URL_STRING = "https://api.data.gov.sg/v1/transport/taxi-availability?date_time=" + URLEncoder.encode(mDate, "utf-8");

I wrote it without compiler, so let me know if it is right.

Hope this helps

Date currentTime = Calendar.getInstance().getTime();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
String URL_STRING ="https://api.data.gov.sg/v1/transport/taxi-availability?date_time=" + URLEncoder.encode(formatter.format(currentTime),"UTF-8");

Make sure to handle Exception for URLEncoder.encode()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM