2015-05-29 61 views
0

一種格式,我有兩個日期格式字符串中,即:不同的日期字符串在Java

1981年12月7日 和 1991年7月11日

String one_date = "1981-12-07"; 
String another_date = "07-11-1991"; 

,我需要將它們轉換以一種格式。

例如在「yyyy-MM-dd」;

我只想將這個字符串正確地插入到sqlite數據庫中,所以它應該都是相同的格式,好嗎?

java SimpleDataFormat無需檢查就可以吃掉所有東西。

子串在這裏不適合。 有人能告訴我檢查的方法嗎?

+0

您想保留哪種格式? –

+0

我懷疑是否有**(一)檢查方法,你的意思是SimpleDat ** e **格式? –

+0

可能的重複[如何將日期從一種格式轉換爲另一種格式的另一種日期對象而不使用任何棄用的類?](http://stackoverflow.com/questions/12503527/how-do-i-convert-the -date-from-one-format-to-another-date-object-in-another-form) –

回答

1

您需要編寫一個代碼,以便在解析之前區分日期版本。您需要根據您想要解析的字符串的某些特徵自行編寫此代碼。對於這兩個,我會做

if (one_date.split("-")[2].length()==2) { 
    // parse it with yyyy-MM-dd 
} else { 
// parse it with dd-MM-yyyy or something 
} 

您也可以使用.lastIndexOf( ' - ');用於檢查最後一個' - '的位置,性能會更好

當然,我們可以使用.charAt(somePositionIndex)來檢查' - '符號是否是我們希望找到它的地方。

+0

「子串不適合在這裏」 - '+ 1' :) –

+1

最簡單的方法。 substr上的watever – alex111

+0

最簡單的就是'if(one_date。charAt(4)==' - '){one date} else {another date}';-)請記住,通過這種方式,任何驗證都會被自動解析爲「FOOL-XX-YY」將被視爲'一個日期'。 – SubOptimal

0

你可以做這樣的事情:

SimpleDateFormat defaultFormat = new SimpleDateFormat("yyyy-MM-dd"); 
    SimpleDateFormat secondFormat = new SimpleDateFormat("dd-MM-yyyy"); 
    String one_date = "1981-12-07"; 
    String another_date = "07-11-1991"; 
    String[] strs = new String[] { one_date, another_date }; 
    ArrayList<Date> dates = new ArrayList<Date>(); 
    for (String s : strs) { 
     try { 
      if (s.matches("\\d{4}-\\d{2}-\\d{2}")) { 
       dates.add(defaultFormat.parse(s)); 
      } else { 
       dates.add(secondFormat.parse(s)); 
      } 
     } catch (ParseException e) { 
      e.printStackTrace(); 
     } 
    } 
    ArrayList<String> converted = new ArrayList<String>(); 
    for (Date d : dates) { 
     converted.add(defaultFormat.format(d)); 
    } 
    System.out.println(converted); 
0

我你有很多不同的日期格式,我建議你使用natty

下面是如何使用它返回一個日期的例子。一旦你有這個日期,你可以簡單地將其格式化爲任何你想要的。

import com.joestelmach.natty.DateGroup; 
import com.joestelmach.natty.Parser; 
import java.util.Date; 

public class ParseDate { 
    public static Date parse(String date)throws Exception{ 
     Parser parser = new Parser(); 
     List<DateGroup> groups = parser.parse(date); 


     int year; 
     int day=1; 
     int month=1; 
     for(DateGroup group : groups){ 
      for(Date d : group.getDates()){ 
       year=d.getYear(); 
       month=d.getMonth(); 
       day=d.getDay(); 
       Date fixedDate=new Date(year,month,day); 
       return fixedDate; 
      } 
     } 

     throw new Exception("unparsable date"); 
} 
} 
0

其他答案過於複雜。

陷阱對於使用一個格式分析異常

簡單的嘗試解析,捕集所造成的不匹配輸入的異常。如果引發異常,請嘗試其他格式。

另外,避免java.util.Date/.Calendar類。它們出了名的麻煩,現在被java.time包和/或Joda-Time庫所取代。