[英]Date formatting with Century
我有一種方法可以將其中包含世紀的日期格式化為通用格式。 將 cyymmdd 格式的日期格式化為 MM/dd/yyyy。
例子,
Convert 1140711 to o7/11/2014
如果您正在談論以格式轉換字符串:
1140711
到
07/11/2014
DateFormat df1 = new SimpleDateFormat("yyddMM");
DateFormat df2 = new SimpleDateFormat("dd/MM/yyyy");
String dateString = "1140711";
System.out.println(df2.format(df1.parse(dateString.substring(1, dateString.length()))));
據我所知,唯一能夠處理世紀字段的日期時間庫是 Joda-Time。
LocalDate date = DateTimeFormat.forPattern("CyyMMdd").parseLocalDate("1140711");
System.out.println("Century=" + date.getCenturyOfEra()); // 20
String usFormat = DateTimeFormat.forPattern("MM/dd/yyyy").print(date);
System.out.println(usFormat); // output: 07/11/2014
正如您所看到的,世紀的輸入數字“1”被簡單地忽略了,因為 Joda-Time 僅將其他字段評估為有效日期。 我個人會拒絕這樣的世紀輸入,因為我們處於 21 世紀,世紀編號為 20,而不是 1。所以 Joda-Time 在這里有其限制,但您是否真的確定您輸入的世紀為 1,或者這只是一個錯字嗎?
我不得不做相反的事情,將日期轉換為 cyyMMdd。
String centuryCharacterOfDateFormat(LocalDate valueDate) {
int year = valueDate.getYear();
int yearMinus1900 = year - 1900;
if (yearMinus1900 < 0) {
throw new PipRuntimeException("Invalid value date, because it is before 1900. " + valueDate);
} else if (yearMinus1900 < 100) {
return "0";
} else {
String strVal = String.valueOf(yearMinus1900);
char hundredthChar = strVal.charAt(strVal.length() - 3);
return String.valueOf(hundredthChar);
}
}
您可以使用類似的邏輯進行相反的轉換。 要獲得年份,您可以添加 1900 和數百個第一個字符。
在示例日期字符串的下面方法中,遵循世紀日期格式“CYYMMDD”,其中 C 代表世紀,YY 代表年份,MM 代表月份,DD 代表日期。 世紀值如下所述:如果世紀值為 0,則表示 20 世紀,1900 年至 1999 年黑白。如果世紀值為 1,則表示 21 世紀,2000 年至 2999 年黑白。
public LocalDate convertedDate () { String dateString = "1230124";
int century = Integer.parseInt(dateString.substring(0, 1));
int year = Integer.parseInt(dateString.substring(1, 3));
int month = Integer.parseInt(dateString.substring(3, 5));
int day = Integer.parseInt(dateString.substring(5, 7));
LocalDate ld= LocalDate.of((century + 19) * 100 + year, month, day);
System.out.printl**strong text**n("Converted Date : "+ld);
返回 ld; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.