how to compare date format

13.3k views Asked by At

My application displays dates in different formats based on user settings. I want to test that it displays correct date format. I have the displayed date as a string (2014/12/31). I do not want to verify the actual date, but just the format.

Ex: When user selects yyyy/dd/MM format, it should display it in that format.

4

There are 4 answers

6
Ankur Singhal On BEST ANSWER

1.) try and parse the String to the required Date using something like SimpleDateFormat

 Date date = null;
    boolean checkformat;
    try {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/dd/MM");
        dateFormat.setLenient(false);
        date = dateFormat.parse("2013/25/09");
    } catch (ParseException ex) {
        ex.printStackTrace();
    }
    if (date == null) {
        checkformat = false;
    } else {
        checkformat = true;
    }

    System.out.println(checkformat);

check like above.

2.) Other approach can be to use regex, but then you have to inbuilt few supported data format regex in your application, and pick accordingly. Play around the {2}, {2}, {4} values inside curly braces to prepare regex.

public static void main(String[] args) throws ParseException {
        String input = "2014/12/31";
        boolean checkformat;
        if (input.matches("([0-9]{4})/([0-9]{2})/([0-9]{2})")) // for yyyy/MM/dd format
            checkformat = true;
        else
            checkformat = false;

        System.out.println(checkformat);
    }

more info here

0
zzm On

you can use regex to check your date string format, like this:

public static void main(String[] args) {
    String date = "2014/11/01";
    Pattern pattern = Pattern.compile("\\d{4}/\\d{2}/\\d{2}");
    Matcher matcher = pattern.matcher(date);
    if (matcher.matches()) {
        System.out.printf("the date string match format:%s", "yyyy/mm/dd");
    }
}
1
Scary Wombat On

If you want to test for 4 patterns then have 4 simpleDateFormat objects and test each one in turn

If the String does not match then it will throw an exception which can be caught.

0
ianaya89 On

You need to implement a custom solution, JavaScript does not have a format date functionality. If you need to handle several formats it could be a hard work and a waste of time.

I recommend use moment.js, a library to manipulate dates easy in JavaScript.

Usage Example:

HTML

 <script src="moment.js"></script>

JS

var now = moment();
now.format("yyyy/dd/MM");