01: String parsing & date formatting – complete the given code

Q. Complete the method “changeDateFormat(String paragraph)” which takes a string input containing dates in mm/dd/yyyy format and converts them to “dd/mm/yyyy” format. For example, “My birthday is on 04/25/1980” becomes “My birthday is on 25/04/1980

A. Here is the solution.

Key Points

1. Fail fast by checking for “paragraph == null || paragraph.length() == 0”.

2. Define date formats for input (i.e. mm/dd/yyyy) and output (i.e. dd/mm/yyyy) formats with “SimpleDateFormat” class.

3. Split the input string into tokens on space with regex\\s+“, which means 1 or more spaces. The dates “07/25/2015” and 08/09/2015 will be one of the tokens along with the other tokens like “The”, “season”, “started”, and so on..

4. Loop through the tokens and whenever a token contains “/”, it could be date, so try to apply the output format. If it was not a date, but just a “/”, an exception will be thrown and ignored.

5. If it was a date token, replace the input format with the output format using “indexof” to find the position and “replace”.

Can this be solved by applying the regular expressions?

Using a regex as shown below will validate the digits, but NOT the actual dates. Regex would not know that you can’t have 30 days in the month of February.

So, you still need to apply the “SimpleDateFormat” to validate the date. Here is the revised solution with regular expressions.

The output on both approaches will be:

More coding challenges to sharpen your programming skills in Java

1. 13 More coding problems & solutions

2. 20+ Can you write Java code? type coding problems

3. Beginner level, what is wrong with this code?

4. Java OOP coding problems & solutions

5. Java data structures & algorithms with diagrams


300+ Java & Big Data Interview FAQs

16+ Java Key Areas Interview Q&As

800+ Java Interview Q&As

300+ Java & Big Data Tutorials

Top