[英]Check if date String contains a year
I have two Strings 我有两个琴弦
String withYear = "12/04/1988"
String withoutYear = "10/04"
The date format is MM/dd/yyyy 日期格式为MM / dd / yyyy
I am trying to determine whether a string contains a year or not . 我试图确定一个字符串是否包含年份 。
Here is my code so far : 到目前为止,这是我的代码:
Calendar c= Calendar.getInstance();
c.setTime(dt.parse(withYear)); //dt is a SimpleDateFormat 'MM/dd/yyyy'
c.get(Calendar.YEAR) // = 1988
c.setTime(dt.parse(withoutYear));
c.get(Calendar.YEAR);// = 1970
I think the easiest way to do this is to forget about making Date/Calendar objects altogether. 我认为最简单的方法是完全放弃制作Date / Calendar对象。 You can simply check the String to see how many sections it has: 您可以简单地检查字符串以查看其包含多少部分:
public static boolean containsYear(String dateStr){
return dateStr.split("/").length == 3;
}
Your code is working perfectly, when you call dt.parse(withoutYear), the year is set automatically to the Epoch year (1970). 您的代码运行良好,当您调用dt.parse(withoutYear)时,年份将自动设置为纪元年份(1970)。
From SimpleDateFormat: http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html 从SimpleDateFormat: http : //docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
This parsing operation uses the calendar to produce a Date. 此解析操作使用日历生成日期。 All of the calendar's date-time fields are cleared before parsing, and the calendar's default values of the date-time fields are used for any missing date-time information. 在解析之前,将清除所有日历的日期时间字段,并且将日历的日期时间字段的默认值用于任何缺少的日期时间信息。 For example, the year value of the parsed Date is 1970 with GregorianCalendar if no year value is given from the parsing operation. 例如,如果没有从解析操作中给出年份值,则使用Date的年份的日期解析为1970,使用GregorianCalendar。 (emphasis mine) (强调我的)
If you don't expect any valid year values as 1970 then you can assume all dates with year==1970 were specified without a year. 如果您不希望任何有效的年份值为1970,则可以假定指定的year == 1970的所有日期都没有年份。
A more complete solution would be to subclass GregorianCalendar and make the default value for field YEAR = -1;
一个更完整的解决方案是将GregorianCalendar子类化并为YEAR = -1;
字段设置默认值YEAR = -1;
String data[] = withYear.split("/");
String year =null ;
if(data.length==3){
year = data[2] ;
System.out.println(year);
}
If you want, you can use YodaTime, its very easy to deal with time/dates, more about it here Yoda time getYear() . 如果需要,您可以使用YodaTime,它非常容易处理时间/日期,在此处可以了解更多有关Yoda time getYear()的信息 。 You can try to parse your String and then getYear(). 您可以尝试解析您的String,然后解析getYear()。
Hope this helps. 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.