简体   繁体   English

java 程序接受任何格式的日期作为输入并打印月份,

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

java program to accept any format of date as input and print the month, java 程序接受任何格式的日期作为输入并打印月份,

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){}    


    }


}

No, it's not.不,这不对。 How would it distinguish 01/02/2011 (dd/MM/yyyy) and 01/02/2011 (MM/dd/yyyy)?它如何区分 01/02/2011 (dd/MM/yyyy) 和 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:这是 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: 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.这是一个快速的概念证明,而不是认真尝试编写这样的 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 eg is 03/04/10 the third of april or the fourth of march?考虑英国与美国日期的简单问题,例如 03/04/10 是 4 月 3 日还是 3 月 4 日?

No, it is not possible.不,这是不可能的。

Proof by counter example: 10/11/12 .反例证明: 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 .仅当您还告诉它格式是什么时才有可能,例如使用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.如果您在 GUI 中编写此代码,那么您可能想要使用单选按钮并将它们放在单选组中。 Otherwise if this is just for use within the compiler (such as a school program) then just use a switch statement like so:否则,如果这仅用于编译器(例如学校程序),则只需使用如下 switch 语句:

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.就像那样,或者您可以只使用一系列 if-else 语句,因为这基本上就是 switch 语句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM