簡體   English   中英

將字符串解析為日期格式

[英]parse string into date format

我正在通過opencsv從csv文件導入數據以插入到mysql數據庫中。 opencsv作為字符串導入,對於數據庫中的1個字段,我需要以yyyy-MM-dd格式將其解析為最新日期。 但是我遇到一個錯誤。

// This is the string that I have extracted from the csv file           
String elem1 = nextLine[0];

// printing out to console I can see the string I wish to convert
System.out.println(elem1); => 2015-08-14

// Below is my code to parse the date

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date convertedCurrentDate = sdf.parse(elem1);
String date=sdf.format(convertedCurrentDate );

// printing date to console gives me 2015-08-14
System.out.println(date);

如上所述,打印日期到控制台給了我2015-08-14。 但是我得到了錯誤:

java.text.ParseException: Unparseable date: "" 

有人可以給我一些有關我做錯事情的建議嗎?

行'java.util.Date convertedCurrentDate = sdf.parse(elem1);' 是導致錯誤的行。

謝謝!

我也很沮喪,以下測試通過了我的機器

public class DateFormatterTest {

private static final String TEST_DATE = "2015-08-14";

   @Test
   public void SimpleDateFormatTest() throws ParseException {
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
      java.util.Date convertedCurrentDate = sdf.parse(TEST_DATE);
      String date=sdf.format(convertedCurrentDate );
      assertEquals(TEST_DATE, date);
   } 

}

您正在運行什么版本的Java? 我知道最新的Java 8(8u61)和JodaTime中存在問題。

另外,請嘗試進行上述測試,以消除除日期代碼之外的所有內容。

這是執行此操作的簡單示例:

SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
String dateInString = "7-Jun-2013";
try {
    Date date = formatter.parse(dateInString);
    System.out.println(date);
    System.out.println(formatter.format(date));
} catch (ParseException e) {
    e.printStackTrace();
}

Java 8更新

String string = "August 21, 2015";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM d, yyyy", Locale.ENGLISH);
LocalDate date = LocalDate.parse(string, formatter);
System.out.println(date); // 2015-09-21

我認為這就是您想要的。很高興為您提供幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM