-1

The code below is the best I have come up with so far. The .setTime() methods are throwing a exception. Is there a better way to do this or correct this?

    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());
    }
rdm
  • 1
  • 2
  • 1
    NPE alert! :) Initialize your calendars with `Calendar.getInstance()`. – Tunaki Sep 27 '15 at 16:52
  • @rdm Glad to see you want participate in StackOverflow. Please search before posting. This site is meant to be a library of authoritative Questions and Answers, not an open-ended discussion group. – Basil Bourque Sep 27 '15 at 17:09
  • You say in title you need to "parse a date string into a Joda DateTime", but in comments to both answers you said you "need a calendar object". We can't help when *you* don't even know what you want. – Andreas Sep 28 '15 at 01:54
  • @ Andreas You're right. Ill make that correction. Im a bit of a novice so a bit of a learning curve. – rdm Sep 28 '15 at 03:22

2 Answers2

0

Seems fine if you fix the initialization of the Calendar variables:

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

The problem would have been more obvious if you had used the correct exception type as recommended, instead of the generic Exception, and printing the stack trace instead of e.getMessage():

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

The stack trace would have told you the exact line where NullPointerException was thrown.

janos
  • 120,954
  • 29
  • 226
  • 236
0

You already created the DateTimeFormatter that your need, so just use it:

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

No need for a SimpleDateFormat or a Calendar.

Note: I fixed the creation of the DateTimeFormatter to Joda, since you were doing it the Java 8 way.

Andreas
  • 154,647
  • 11
  • 152
  • 247