Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
774 views
in Technique[技术] by (71.8m points)

java - How to extract a date in a specific format from URL using Selenium?

Using:

String URL = driver.getCurrentUrl();

I get something like this:

firstname=&lastname=&sex=Male&exp=1&datepicker=11%2F30%2F2020&photo=&continents=asia&submit=

I have to extract the date and to print it in this format: yyyy-mm-dd, that is, to get 2020-11-30. Does anyone have any idea? Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I'm going to assume that getCurrentUrl() returns the full url not just the query string.

At a high level I see the process as

  1. Url decode the string
  2. Parse the query string into a map
  3. Transform the datepicker value from mm-dd-yyyy to yyyy-mm-dd which is just iso8601

Steps 1 and 2 can be done with a library such as OkHttp

final HttpUrl currentUrl = HttpUrl.parse(driver.getCurrentUrl());
if (currentUrl != null) {
    final String inputDate = currentUrl.queryParameter("datepicker");
}

If you don't want to use a/that library there are some zero dependency options in this other question.

Step 3 has some options depending how robust you need this.

  1. Direct string manipulation.
  2. Use a library or built in date utility.

If this doesn't matter much the string manipulation would be the simplest. Just create a new string with the yyyy, a '-', and the mm-dd.

The downside is that it doesn't offer any way to validate the date.

Here is a library option

SimpleDateFormat parseFormatter = new SimpleDateFormat("dd-MM-yyyy");
Date date = parseFormatter.parse(inputDate);

SimpleDateFormat outputFormatter = new SimpleDateFormat("yyyy-MM-dd");

String date = outputFormatter.format(date);
System.out.println(date);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...