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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5898250/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 13:20:06  来源:igfitidea点击:

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

java

提问by user617597

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


    }


}

回答by JB Nizet

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)?

回答by Sean Patrick Floyd

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.

这是概念的快速证明,而不是编写这样一个类的认真尝试。这将匹配许多无效格式并忽略许多有效格式。

回答by Adrian Mouat

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?

对于各种格式,是的,这是可能的。对于任何格式,不,不是。考虑英国与美国日期的简单问题,例如 03/04/10 是四月三日还是三月四日?

回答by Dilum Ranatunga

No, it is not possible.

不,这是不可能的。

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

反例证明:10/11/12. 这是一种“有效”格式……但是月份是几月?

回答by Alan Escreet

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

仅当您还告诉它格式是什么时才有可能,例如使用Locale

回答by user740005

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:

从技术上讲,它不是,但您可以做的是提供一些选项来让用户选择他们的格式。如果您在 GUI 中编写它,那么您可能需要使用单选按钮并将它们放在一个单选组中。否则,如果这只是在编译器中使用(例如学校程序),那么只需使用像这样的 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 语句。