Java 以这种格式从字符串解析日期:dd/MM/yyyy [到 dd/MM/yyyy]

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3386520/
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-08-13 22:49:41  来源:igfitidea点击:

Parse Date from String in this format : dd/MM/yyyy [to dd/MM/yyyy]

javaregexstring

提问by Yijinsei

I thinking what is the best way in Java to parse the String with this format dd/MM/yyyy [to dd/MM/yyyy]. The string with the [] are optional and dd stand for the 2 digit presentation of dates, MM is the 2 digit presentation of month and yyyy is the 4 digit presentation of year.

我想在 Java 中用这种格式 dd/MM/yyyy [到 dd/MM/yyyy] 解析字符串的最佳方法是什么。带 [] 的字符串是可选的,dd 代表日期的 2 位数表示,MM 是月份的 2 位数表示,yyyy 是年份的 4 位数表示。



Update

更新

Thanks guys for the fast response, however I forgot to tell you the [] is to symbolize optional, there is no [] in the string a sample String might be

感谢大家的快速响应,但是我忘了告诉你 [] 是象征可选的,字符串中没有 [] 一个示例字符串可能是

  • 22/01/2010
  • 22/01/2010 to 23/01/2010
  • null
  • 22/01/2010
  • 22/01/2010 至 23/01/2010
  • 空值

Current I wrote the code this way, work but is ugly =(

目前我以这种方式编写代码,工作但很丑=(

String _daterange = (String) request.getParameter("daterange");
    Date startDate = null, endDate = null;
    // Format of incoming dateRange is 
    if (InputValidator.requiredValidator(_daterange)) {
        String[] _dateRanges = _daterange.toUpperCase().split("TO");
        try {
            startDate = (_dateRanges.length > 0) ? sdf.parse(_dateRanges[0]) : null;
            try{
                endDate = (_dateRanges.length > 1) ? sdf.parse(_dateRanges[1]) : null;
            }catch(Exception e){
                endDate = null;
            }
        } catch (Exception e) {
            startDate = null;
        }
    }

采纳答案by duffymo

Use java.text.DateFormatand java.text.SimpleDateFormatto do it.

使用java.text.DateFormatjava.text.SimpleDateFormat来做。

DateFormat sourceFormat = new SimpleDateFormat("dd/MM/yyyy");
String dateAsString = "25/12/2010";
Date date = sourceFormat.parse(dateAsString);

UPDATE:

更新:

If you have two Dates hiding in that String, you'll have to break them into two parts. I think others have pointed out the "split" idea. I'd just break at whitespace and throw the "TO" away.

如果您在该字符串中隐藏了两个日期,则必须将它们分成两部分。我认为其他人已经指出了“分裂”的想法。我只是在空格处中断并将“TO”扔掉。

Don't worry about efficiency. Your app is likely to be riddled with inefficiencies much worse than this. Make it work correctly and refactor it only if profiling tells you that this snippet is the worst offender.

不要担心效率。您的应用程序可能充斥着比这更糟糕的低效率。使其正常工作并仅在分析告诉您此代码段是最严重的违规者时才对其进行重构。

回答by dogbane

Something like this should do the trick:

像这样的事情应该可以解决问题:

String input = "02/08/2010 [to 31/12/2010]";
DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Date d  = format.parse(input.split(" ")[0]);
System.out.println(d) ;

回答by Neel

you can do something like this -

你可以做这样的事情 -

String input = "02/08/2010 [to 31/12/2010]";
    java.text.DateFormat format = new java.text.SimpleDateFormat("dd/MM/yyyy");
    java.util.Date d = null;
    try {
        d = format.parse(input.split(" ")[0]);
    } catch (java.text.ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println(d) ;

if string with the [] is not present still input.split(" ")[0]will return the first string only.

如果带有 [] 的字符串不存在,则仍将input.split(" ")[0]仅返回第一个字符串。

回答by Basil Bourque

tl;dr

tl;博士

LocalDate.parse( 
    "22/01/2010" , 
    DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) 
)

…more…

…更多的…

// String input is:
// (a) long: "22/01/2010 to 23/01/2010". 
// (b) short: "22/01/2010".
// (c) null.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ;

if( input.length() == 24 ) {           // Ex: "22/01/2010 to 23/01/2010"
    List<LocalDate> lds = new ArrayList<>( 2 );
    String[] inputs = input.split( " to " );
    for( String nthInput : inputs ) {
        LocalDate ld = LocalDate.parse( nthInput , f ) ;
        lds.add( ld );
    }
    … // Do what you want with `LocalDate` objects collection.

} else if( input.length() == 10 ) {    // Ex: "22/01/2010"
    LocalDate ld = LocalDate.parse( input , f ) ;
    … // Do what you want with `LocalDate` object.

} else if( null == input ) {
    … // Decide what you want to do for null input.

} else {
    System.out.println( "Unexpected input: " + input ) ;
}

See this code run live at IdeOne.com.

查看此代码在 IdeOne.com 上实时运行

Using java.time

使用 java.time

The other Answers use troublesome old date-time classes that are now legacy, supplanted by the java.time classes.

其他答案使用麻烦的旧日期时间类,这些类现在是遗留的,由 java.time 类取代。

As for handling multiple types of strings, look at the length of the string.

至于处理多种类型的字符串,看字符串的长度。

if( input.length() == 10 ) { … }

If long, split on the 4-character substring “ to ”.

如果很长,则拆分为 4 个字符的子字符串“ to ”。

String[] inputs = "22/01/2010 to 23/01/2010".split( " to " );

Parse the date string as a LocalDate.

将日期字符串解析为LocalDate.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" );
LocalDate ld = LocalDate.parse( "22/01/2010" , f );


About java.time

关于java.time

The java.timeframework is built into Java 8 and later. These classes supplant the troublesome old legacydate-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

java.time框架是建立在Java 8和更高版本。这些类取代了麻烦的旧的遗留日期时间类,例如java.util.Date, Calendar, & SimpleDateFormat

The Joda-Timeproject, now in maintenance mode, advises migration to the java.timeclasses.

现在处于维护模式Joda-Time项目建议迁移到java.time类。

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

要了解更多信息,请参阅Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范是JSR 310

You may exchange java.timeobjects directly with your database. Use a JDBC drivercompliant with JDBC 4.2or later. No need for strings, no need for java.sql.*classes.

您可以直接与您的数据库交换java.time对象。使用符合JDBC 4.2或更高版本的JDBC 驱动程序。不需要字符串,不需要类。java.sql.*

Where to obtain the java.time classes?

从哪里获得 java.time 类?

The ThreeTen-Extraproject extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

ThreeTen-额外项目与其他类扩展java.time。该项目是未来可能添加到 java.time 的试验场。你可能在这里找到一些有用的类,比如IntervalYearWeekYearQuarter,和更多