Total Pageviews

2014/12/22

How to Determine if the Date Format is Correct or Not in Java

Problem
We hope the date parameter should be yyyyMMdd format and only accept Western calendar system. 
If user provide a date parameter with Minguo calendar, it should return error to user.

Solution
This DateUtils class provides an isCorrectDateFormatWithWesternYear method, it will

  • return false if date format is incorrect
  • return true if date format is correct

We define the expected format in Line 24.
Set lenient to false with strict parsing, and call parse method to check the parse result.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package gov.nta.dbm.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;

import lombok.extern.slf4j.Slf4j;

/**
 * The Class DateUtils.
 */
@Slf4j
public class DateUtils {

    /**
     * Checks if is correct date format with western year.
     * 
     * @param dateStr
     *            the date str
     * @return the boolean
     */
    public static Boolean isCorrectDateFormatWithWesternYear(String dateStr) {
        Boolean isCollect = Boolean.FALSE;
        // instantiate SimpleDateFormat object with specific date format
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        try {
            // Specify whether or not date/time parsing is to be lenient. With lenient parsing, the
            // parser may use heuristics to interpret inputs that do not precisely match this
            // object's format. With strict parsing, inputs must match this object's format
            dateFormat.setLenient(false);
            // call parse method, return true if parse successfully, return false if fail to parse.
            dateFormat.parse(dateStr);
            isCollect = Boolean.TRUE;
        } catch (ParseException e) {
            isCollect = Boolean.FALSE;
            e.printStackTrace();
        }
        return isCollect;
    }

    /**
     * The main method.
     * 
     * @param args
     *            the arguments
     */
    public static void main(String[] args) {
        log.debug("test1=" + DateUtils.isCorrectDateFormatWithWesternYear("20141231"));
        log.debug("test1=" + DateUtils.isCorrectDateFormatWithWesternYear("1031222"));
    }

}

In main method, we input "20141231" and "1031222" to do test, and here is the test result:
1
2
3
4
5
6
15:34:00.446 [main] DEBUG gov.nta.dbm.utils.DateUtils - test1=true
java.text.ParseException: Unparseable date: "1031222"
 at java.text.DateFormat.parse(DateFormat.java:357)
 at gov.nta.dbm.utils.DateUtils.isCorrectDateFormatWithWesternYear(DateUtils.java:31)
 at gov.nta.dbm.utils.DateUtils.main(DateUtils.java:48)
15:34:00.453 [main] DEBUG gov.nta.dbm.utils.DateUtils - test1=false


Reference
[1] http://docs.oracle.com/javase/7/docs/api/java/text/DateFormat.html

No comments: