简体   繁体   English

如何更改日期格式以解析为url_string?

[英]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). 我正在使用API​​通过Android(java)中的URL链接检索出租车数据。

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. 但是,日期和时间2018-07-17T18%3A49%3A00是硬编码的,我希望使用当前日期和时间动态地完成此操作。

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. 我收到来自API服务器的空响应。 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: 一种可能的解决方案是使用本机方法对URL进行编码:

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 ). 另一个问题是格式设置有误,请参考官方文档 YYYY yyyy ,您的分钟时间应为mm而不是MMMM为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() 确保处理URLEncoder.encode()的异常

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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