Java 解析 MM/DD/YY 格式的日期并将其调整为当前/上一个世纪的最佳方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/251535/
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
What is the best way to parse a date in MM/DD/YY format and adjust it to the current / previous century?
提问by ScArcher2
One of our customers wants to be able to enter a date with only 2 digits for the year component. The date will be in the past, so we want it to work for the previous century if the 2 digit year is after the current year, but work for the current century if the 2 digit year is equal to or less than the current year.
我们的一位客户希望能够输入一个只有 2 位数字的日期作为年份部分。日期将是过去,因此如果 2 位数年份在当前年份之后,我们希望它适用于上一个世纪,但如果 2 位数年份等于或小于当前年份,则适用于当前世纪。
as of today 10/30/2008
截至今天 10/30/2008
01/01/01 = 01/01/2001
01/01/01 = 01/01/2001
01/01/09 = 01/01/1909
01/01/09 = 01/01/1909
This is a strange requirement, and I solved the problem, I just don't like my solution. It feels like there is a better way to do this.
这是一个奇怪的要求,我解决了这个问题,我只是不喜欢我的解决方案。感觉有更好的方法可以做到这一点。
Thanks for the help.
谢谢您的帮助。
public static String stupidDate(String dateString)
{
String twoDigitYear = StringUtils.right(dateString, 2);
String newDate = StringUtils.left(dateString, dateString.length() - 2);
int year = NumberUtils.toInt(twoDigitYear);
Calendar c = GregorianCalendar.getInstance();
int centuryInt = c.get(Calendar.YEAR) - year;
newDate = newDate + StringUtils.left(Integer.toString(centuryInt), 2) + twoDigitYear;
return newDate;
}
采纳答案by Ken Gentle
Groovy script (easy enough to throw into java) demonstrating the point @bobince made about SimpleDateFormat.
Groovy 脚本(很容易扔到 java 中)演示了@bobince 关于 SimpleDateFormat 的观点。
import java.text.SimpleDateFormat
SimpleDateFormat sdf = new SimpleDateFormat('MM/dd/yy')
SimpleDateFormat fmt = new SimpleDateFormat('yyyy-MM-dd')
Calendar cal = Calendar.getInstance()
cal.add(Calendar.YEAR, -100)
sdf.set2DigitYearStart(cal.getTime())
dates = ['01/01/01', '10/30/08','01/01/09']
dates.each {String d ->
println fmt.format(sdf.parse(d))
}
Yields
产量
2001-01-01
2008-10-30
1909-01-01
回答by matt b
How about this:
这个怎么样:
public static String anEasierStupidDateWithNoStringParsing(String dateString) {
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
//handling ParseExceptions is an exercise left to the reader!
Date date = df.parse(dateString);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
Calendar now = Calendar.getInstance();
if (cal.after(now)) {
cal.add(Calendar.YEAR, -100);
}
return cal;
}
In other words, let SimpleDateFormat parse the String and just adjust the year to be the previous century if SimpleDateFormat (which has it's own rules for interpreting year strings) returns a date that is after the current date.
换句话说,如果 SimpleDateFormat(它有自己的解释年份字符串的规则)返回当前日期之后的日期,则让 SimpleDateFormat 解析 String 并将年份调整为上一个世纪。
This would guarantee that all dates returned are in the past. However, it doesn't account for any dates that might be parsed as beforethis past century - for example, with the format MM/dd/yyyy
, a date string like "01/11/12" parses to Jan 11, 12 A.D.
这将保证所有返回的日期都是过去的。但是,它不考虑可能像上个世纪之前那样解析的任何日期- 例如,使用 format MM/dd/yyyy
,像“01/11/12”这样的日期字符串解析为公元 12 年 1 月 11 日
回答by Hyman Leow
If Joda Time is an option:
如果 Joda Time 是一个选项:
String inputDate = "01/01/08";
// assuming U.S. style date, since it's not clear from your original question
DateTimeFormatter parser = DateTimeFormat.forPattern("MM/dd/yy");
DateTime dateTime = parser.parseDateTime(inputDate);
// if after current time
if (dateTime.isAfter(new DateTime())) {
dateTime = dateTime.minus(Years.ONE);
}
return dateTime.toString("MM/dd/yyyy");
I know Joda Time isn't part of Java SE, and as I've said in another thread, I usually do not condone using a third-party library when there's a Java library that does the same thing. However, the person who is developing Joda Time is also leading JSR310 - the Date and Time API that'll make it into Java 7. So I Joda Time is basically going to be in future Java releases.
我知道 Joda Time 不是 Java SE 的一部分,正如我在另一个线程中所说的那样,当有一个 Java 库可以做同样的事情时,我通常不会容忍使用第三方库。然而,开发 Joda Time 的人也在领导 JSR310 - 日期和时间 API,它将使其成为 Java 7。所以我 Joda Time 基本上会出现在未来的 Java 版本中。
回答by bobince
SimpleDateFormat already does two-digit year parsing for you, using the two-letter ‘yy' format. (It'll still allow four digits, obviously.)
SimpleDateFormat 已经使用两个字母的 'yy' 格式为您解析了两位数的年份。(显然,它仍然允许四位数。)
By default it uses now-80→now+20, so it's not exactly the same rule you propose, but it's reasonable and standardised (in the Java world at least), and can be overridden using set2DigitYearStart() if you want.
默认情况下,它使用 now-80→now+20,因此它与您提出的规则不完全相同,但它是合理且标准化的(至少在 Java 世界中),并且可以根据需要使用 set2DigitYearStart() 覆盖。
DateFormat informat= new SimpleDateFormat("MM/dd/yy");
DateFormat outformat= new SimpleDateFormat("MM/dd/yyyy");
return outformat.format(informat.parse(dateString));
In the longer term, try to migrate to ISO8601 date formatting (yyyy-MM-dd), because MM/dd/yy is approximately the worst possible date format and is bound to cause problems eventually.
从长远来看,尝试迁移到 ISO8601 日期格式 (yyyy-MM-dd),因为 MM/dd/yy 大约是最糟糕的日期格式,最终势必会导致问题。
回答by Steve McLeod
The best way is to use the Joda Time API for dates and times in Java.
最好的方法是在 Java 中使用 Joda Time API 来获取日期和时间。
回答by chetan singhal
Date deliverDate = new SimpleDateFormat("MM/dd/yy").parse(deliverDateString);
String dateString2 = new SimpleDateFormat("yyyy-MM-dd").format(deliverDate);
Working for me.
为我工作。
回答by Basil Bourque
Pivot Year In Joda-Time
Joda 时间的枢轴年
The excellent Joda-Time 2.5 library includes this functionality. No need to write any code yourself. Simply call withPivotYear()
on a DateTimeFormatter
. See that linked doc for examples of how to use it.
优秀的 Joda-Time 2.5 库包含此功能。无需自己编写任何代码。只需调用withPivotYear()
一个DateTimeFormatter
. 有关如何使用它的示例,请参阅链接的文档。