Calculating date/time diff

  • Replies:1
Suresh Kumar
  • Forum posts: 9

Sep 3, 2018, 9:30:06 PM via Website

I am quite new to Android development. I need to get the difference(duration) between two data/time values. When I try to get the difference between to date/times I guess the app is crashing. Heres the code:

                 // txtStartDate text = 4/8/2018

                          // txtStartTiem text = 11:16 PM


              // txtEndDate text = 4/8/2018
             // txtEndtime text = 12:30 (0:30 AM)


            String format ="yyyy-MM-dd'T'HH:mm:ss" ;//“yyyy-MM-dd’T’HH:mm:ss”;
                        SimpleDateFormat simpleFormat = new SimpleDateFormat(format);
                        String strStartDateText = txtStartDate.getText().toString() + " " + txtStartTime.getText().toString();
                        Date startDate = simpleFormat.parse(strStartDateText  , new ParsePosition(1));

                        String strEndDateText = txtEndDate.getText().toString() + " " + txtEndTime.getText().toString();
                        Date EndDate = simpleFormat.parse(strEndDateText  , new ParsePosition(1));



                        long different = EndDate.getTime() - startDate.getTime(); // suspected crash.

What could be wrong here?

Reply
James Watson
  • Forum posts: 1,584

Sep 4, 2018, 4:24:20 AM via Website

The simpleFormat doesn't match the format of value of txtStartDate & txtEndDate.
So, both startDate and EndDate are null before you get the 'different' value.
You had better use 'try ... catch' and process these exceptions.

Download size < 0.15 MB. But also accurate enough, ad-free & free.
The minimalist app available on Play Store: https://goo.gl/ws42fN
Blog: https://okblackcafe.blogspot.com Your 5-star is appreciated.

Helpful?
Reply