Java, to accept any date format as input and print the month,

java-program for accepting any date format as input and print of the month,

Is it possible

I tried the following, any other alternative ways / ideas?

import java.text.*;

import java.util.*;


public class PrintMonth3{


    public static void main(String args[])throws Exception{

    String patterns[]={"dd.MM.yyyy","dd.MM.yy","dd.MMM.yyyy","dd.MMM.yy","d.MM.yyyy"};

    String input="4.06.2011";

    for(int i=0;i<patterns.length;i++)
        doPrintMonth(patterns[i],input);

    System.out.println("\nNot a valid date format..");


    }



    public  static void doPrintMonth( String pattern,String input ) {


    try{
    SimpleDateFormat sdf=new SimpleDateFormat(pattern);

    Date output=sdf.parse(input);


    String mon[]={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
    int m=output.getMonth();
    System.out.println("\n\t" + mon[m] );
    System.exit(0);
    }
    catch(Exception e){}    


    }


}
+3
source share
6 answers

For a reason, yes. Here is a working example that accepts various formats.

I assume the German / European format as follows:

DD. MM. YYYY HH:MM:SS:MMMM

(this means that I cannot match any date format where the month is coming)

Here's the class:

public class VariableDateParser {

    private static final Pattern DATE_PATTERN = Pattern
    .compile("((?:(?:\\d+(?:[./]\\s*)?)+)?)\\s*((?:(?:\\d+[:]?)+)?)");

    public Date getDate(final String dateString) {
        final Calendar calendar = Calendar.getInstance();
        final Matcher matcher = DATE_PATTERN.matcher(dateString);
        if (matcher.matches()) {
            final String dateGroup = matcher.group(1).trim();
            if (!"".equals(dateGroup)) {
                final Iterator<Integer> fields = Arrays.asList(
                    Calendar.DATE, Calendar.MONTH, Calendar.YEAR).iterator();
                final String[] items = dateGroup.split("\\D+");
                for (final String item : items) {
                    if ("".equals(item))
                        break;
                    else if (fields.hasNext()) {
                        final Integer field = fields.next();
                        calendar.set(field, Integer.parseInt(item) -
                           // months are 0-based, grrrr!!!
                           (field.equals(Calendar.MONTH) ? 1 : 0));
                    } else {
                        throw new IllegalArgumentException(
                            "Bad date part: " + dateGroup);
                    }
                }
            }
            final String timeGroup = matcher.group(2).trim();
            if (!"".equals(timeGroup)) {
                final Iterator<Integer> fields = Arrays.asList(
                    Calendar.HOUR, Calendar.MINUTE, Calendar.SECOND,
                    Calendar.MILLISECOND).iterator();
                final String[] items = timeGroup.split("\\D+");
                for (final String item : items) {
                    if ("".equals(item))
                        break;
                    else if (fields.hasNext()) {
                        final Integer field = fields.next();
                        calendar.set(field, Integer.parseInt(item));
                    } else {
                        throw new IllegalArgumentException(
                            "Bad time part: " + timeGroup);
                    }
                }
            }

        } else
            throw new IllegalArgumentException(
                "Bad date string: " + dateString);
        return calendar.getTime();
    }

}

Test code:

public static void main(final String[] args) {
    VariableDateParser parser = new VariableDateParser();
    DateFormat df = DateFormat.getDateTimeInstance(
        DateFormat.MEDIUM, DateFormat.LONG, Locale.GERMAN);
    System.out.println(df.format(parser.getDate("11")));
    System.out.println(df.format(parser.getDate("11. 10.")));
    System.out.println(df.format(parser.getDate("11. 10. 4")));
    System.out.println(df.format(parser.getDate("11. 10. 2004")));
    System.out.println(df.format(parser.getDate("11. 10. 2004 11")));
    System.out.println(df.format(parser.getDate("11. 10. 2004 11:35")));
    System.out.println(df.format(parser.getDate("11. 10. 2004 11:35:18")));
    System.out.println(df.format(parser.getDate("11. 10. 2004 11:35:18:123")));
    System.out.println(df.format(parser.getDate("11:35")));
    System.out.println(df.format(parser.getDate("11:35:18")));
    System.out.println(df.format(parser.getDate("11:35:18:123")));
}

Conclusion:

11.05.2011 15:57:24 MESZ
11.10.2011 15:57:24 MESZ
11.10.0004 15:57:24 MEZ
11.10.2004 15:57:24 MESZ
11.10.2004 23:57:24 MESZ
11.10.2004 23:35:24 MESZ
11.10.2004 23:35:18 MESZ
11.10.2004 23:35:18 MESZ
01.05.2011 13:35:24 MESZ
01.05.2011 13:35:18 MESZ
01.05.2011 13:35:18 MESZ

Note:

This is a quick proof of concept, not a serious attempt to write such a class. This will conform to many invalid formats and ignore many acceptable ones.

+4
source

, . 01/02/2011 (dd/MM/yyyy) 01/02/2011 (MM/dd/yyyy)?

+9

, , . . , , 03/04/10 ?

+3

, .

: 10/11/12. "" ... ?

+2

, , , Locale.

+1

Technically, this is not something you can do, it is to provide some options so that the user can choose his own format. If you write this in the graphical interface, you can use the radio buttons and put them in a group of radio stations. Otherwise, if it is easy to use in the compiler (for example, in a school program), simply use the switch statement like this:

Scanner kbReader = new Scanner(System.in);
String format = kbReader.next();//they might enter mm/dd/yy or any format you want.
switch(format)
{
  case "mm/dd/yy": //do coding here
                      break;
  case "dd/mm/yy": //do coding here
                      break;
}

just like that, or you can just use a series of if-else statements because this is basically what the switch statement is.

0
source

All Articles