2015-09-27 41 views
-1

下面的代碼是迄今爲止我所得到的最好的代碼。 .setTime()方法拋出異常。有沒有更好的方法來做到這一點或糾正這一點?如何將日期字符串解析爲java的Joda DateTime對象?

String format = "MM/dd/yyyy"; 

    DateTime test = new DateTime(); 
    DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("MM/dd/yyyy"); 

    SimpleDateFormat formater = new SimpleDateFormat(format); 

    String startDateString = "09/10/2015"; 
    String endDateString = "09/20/2015"; 
    Date startDate = null; 
    Date endDate = null; 
    Calendar sampleDateStart = null; 
    Calendar sampleDateEnd = null; 

    try{ 
     startDate = formater.parse(startDateString); 
     endDate = formater.parse(endDateString); 
     sampleDateStart.setTime(startDate); 
     sampleDateEnd.setTime(endDate); 
    }catch(Exception e){ 
     System.out.println(e.getMessage()); 
    } 
+1

NPE警報! :)用'Calendar.getInstance()'初始化你的日曆。 – Tunaki

+0

@rdm很高興看到你想參與StackOverflow。發帖前請先搜索。本網站旨在成爲一個權威性問答庫,而不是一個開放式討論組。 –

+0

你說在標題中你需要「將日期字符串解析成Joda DateTime」,但是在對兩個答案的評論中,你都說過「需要一個日曆對象」。當你*甚至不知道你想要什麼時,我們無法提供幫助。 – Andreas

回答

0

如果您修復Calendar變量的初始化工作似乎罰款:

Calendar sampleDateStart = Calendar.getInstance(); 
Calendar sampleDateEnd = Calendar.getInstance(); 

的問題會更明顯,如果你已經使用了正確的異常類型的建議, ,而不是通用Exception , 和打印堆棧跟蹤而不是e.getMessage()

try { 
    startDate = formater.parse(startDateString); 
    endDate = formater.parse(endDateString); 
    sampleDateStart.setTime(startDate); 
    sampleDateEnd.setTime(endDate); 
} catch (ParseException e) { 
    e.printStackTrace(); 
} 

堆棧跟蹤會告訴你NullPointerException被拋出的確切行。

0

您已經創建了DateTimeFormatter您的需求,所以才使用它:

DateTimeFormatter formater = DateTimeFormat.forPattern("MM/dd/yyyy"); 
DateTime startDateTime = formater.parseDateTime("09/10/2015"); 
DateTime endDateTime = formater.parseDateTime("09/20/2015"); 

無需一個SimpleDateFormatCalendar

注意:我修正了爲Joda創建DateTimeFormatter,因爲您正在使用Java 8方式。

+0

我需要的最終結果是另一種方法的日曆對象 – rdm

+0

您的第一行還會給我帶來錯誤,提示DateTimeFormat被更改爲DateTimeFormatter。這是爲什麼? – rdm

+0

因爲你實際上沒有安裝Joda? – Andreas

相關問題