FAQ

Java

JSP

Servlet


Advertisement



Why Has No ParseException Exception in Parsing Date String?

Date/time converts to date string or vice versa. It is a common thing in our developer's life. For example,

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
import java.text.ParseException;

public class ConsoleInputExample {

public static void main(String[] args) {

Scanner scanner= new Scanner(System.in);
SimpleDateFormat df = new SimpleDateFormat("mm/dd/yyyy");

try {
do {
System.out.print("ENTER DATE STRING (mm/dd/yyyy or 'q') : ");
String dateString = scanner.next();
if (dateString != null) dateString = dateString.trim();
if (dateString == null || dateString.length()== 0)
continue;
if (dateString.equalsIgnoreCase("Q"))
break;

// Parse the date
try {
Date date = df.parse(dateString);
System.out.println("Original string: " + dateString);
System.out.println("Parsed date : " + date.toString());
System.out.println();
}
catch(ParseException pe) {
System.out.println("ERROR: could not parse date in string \""
 + dateString + "\"");
}

} while (true);
}
catch(Exception e) {
;
}
}
}

Run the above code and enter wrong month, day, and year as following and you did not get ParseException:

ENTER DATE STRING (mm/dd/yyyy or 'q') : 2222/22232/23123123
Original string: 2222/22232/23123123
Parsed date : Mon Nov 14 13:02:00 EST 23123183

Actually, SimpleDateFormat class provides setLenient method for valiadtion of the parsing date/time string. The following code is fine,

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
import java.text.ParseException;

public class ConsoleInputExample {

public static void main(String[] args) {

Scanner scanner= new Scanner(System.in);
SimpleDateFormat df = new SimpleDateFormat("mm/dd/yyyy");
df.setLenient(false);

try {
do {
System.out.print("ENTER DATE STRING (mm/dd/yyyy or 'q') : ");
String dateString = scanner.next();
if (dateString != null) dateString = dateString.trim();
if (dateString == null || dateString.length()== 0)
continue;
if (dateString.equalsIgnoreCase("Q"))
break;

// Parse the date
try {
Date date = df.parse(dateString);
System.out.println("Original string: " + dateString);
System.out.println("Parsed date : " + date.toString());
System.out.println();
}
catch(ParseException pe) {
System.out.println("ERROR: could not parse date in string \""
 + dateString + "\"");
}

} while (true);
}
catch(Exception e) {
;
}
}
}

Here is result,

ENTER DATE STRING (mm/dd/yyyy or 'q') : 2222/22232/23123123
ERROR: could not parse date in string "2222/22232/23123123"
ENTER DATE STRING (mm/dd/yyyy or 'q') :


Printer-friendly version Printer-friendly version | Send this 
article to a friend Mail this to a friend

Previous Next vertical dots separating previous/next from contents/index/pdf Contents

  |   |