[英]Parse Date from String in this format : dd/MM/yyyy [to dd/MM/yyyy]
I thinking what is the best way in Java to parse the String with this format dd/MM/yyyy [to dd/MM/yyyy]. 我想在Java中用这种格式解析String的最佳方法是dd / MM / yyyy [到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. 带[]的字符串是可选的,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 谢谢大家的快速响应,但是我忘了告诉你[]是象征可选的,字符串中没有[]示例字符串可能是
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;
}
}
Use java.text.DateFormat
and java.text.SimpleDateFormat
to do it. 使用java.text.DateFormat
和java.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. 只有当分析告诉你这个片段是最糟糕的罪犯时,才能使它正常工作并重构它。
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上的此代码 。
The other Answers use troublesome old date-time classes that are now legacy, supplanted by the java.time classes. 其他Answers使用麻烦的旧日期时间类,这些类现在是遗留的,由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 );
The java.time framework is built into Java 8 and later. java.time框架内置于Java 8及更高版本中。 These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
. 这些类取代了麻烦的旧遗留日期时间类,如java.util.Date
, Calendar
和SimpleDateFormat
。
The Joda-Time project, now in maintenance mode , advises migration to the java.time classes. 现在处于维护模式的Joda-Time项目建议迁移到java.time类。
To learn more, see the Oracle Tutorial . 要了解更多信息,请参阅Oracle教程 。 And search Stack Overflow for many examples and explanations. 并搜索Stack Overflow以获取许多示例和解释。 Specification is JSR 310 . 规范是JSR 310 。
You may exchange java.time objects directly with your database. 您可以直接与数据库交换java.time对象。 Use a JDBC driver compliant with JDBC 4.2 or later. 使用符合JDBC 4.2或更高版本的JDBC驱动程序 。 No need for strings, no need for java.sql.*
classes. 不需要字符串,不需要java.sql.*
类。
Where to obtain the java.time classes? 从哪里获取java.time类?
The ThreeTen-Extra project extends java.time with additional classes. ThreeTen-Extra项目使用其他类扩展了java.time。 This project is a proving ground for possible future additions to java.time. 该项目是未来可能添加到java.time的试验场。 You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more . 您可以在这里找到一些有用的类,比如Interval
, YearWeek
, YearQuarter
,和更多 。
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) ;
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]
将仅返回第一个字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.