开发者

java program to accept any format of date as input and print the month,

开发者 https://www.devze.com 2023-03-03 07:01 出处:网络
java program to accept any format of date as input and print the month, Is it possible I tried the following,any other alternative ways/ideas??

java program to accept any format of date as input and print 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开发者_C百科","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){}    


    }


}


No, it's not. How would it distinguish 01/02/2011 (dd/MM/yyyy) and 01/02/2011 (MM/dd/yyyy)?


Within reason, yes. Here's a working example that accepts a variety of formats.

I'm assuming a German / European format like this:

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

(which means that I can't match any date format where the month comes first)

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")));
}

Output:

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 of writing such a class. This will match many invalid formats and ignore many valid ones.


For a wide range of formats, yes it is possible. For any format, no it is not. Consider the simple problem of British vs American dates e.g is 03/04/10 the third of april or the fourth of march?


No, it is not possible.

Proof by counter example: 10/11/12. This is a 'valid' format... but what is the month?


It's possible only if you also tell it what the format is, for instance with the Locale.


Technically its not but what you can do is provide some options to get the user to choose their format. If you are writing this in a GUI then you might want to use radio buttons and put them in a radio group. Otherwise if this is just for use within the compiler (such as a school program) then just use a switch statement like so:

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 could just use a series of if-else statements because that is basically what a switch statement is.

0

精彩评论

暂无评论...
验证码 换一张
取 消