0

I'm new to Android and I am having problem while parsing String to Date format. I am trying to retrieve data from Firebase and convert it to Date type.

I have used SimpleDateFormat to parse and its working fine normally. The problem arise only when I try to parse data from Firebase.

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                            Bundle savedInstanceState) {
       View view = inflater.inflate(R.layout.fragment_activity, container, false);
       calT = Calendar.getInstance();
       calD = Calendar.getInstance();
       try {
           today = new SimpleDateFormat("dd-MMM-yy", Locale.getDefault()).parse(stoday); // WORKING FINE
       } catch (ParseException e) {
           e.printStackTrace();
       } 
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                       for (DataSnapshot activitySnapshot : dataSnapshot.getChildren()) {
                           ActivityData activityData = activitySnapshot.getValue(ActivityData.class);
                           DateOfEvent = String.valueOf(activitySnapshot.child("dateOfEvent").getValue());
                           try {
                               date1 = new SimpleDateFormat("dd/MMM/yy",Locale.getDefault()).parse(DateOfEvent); //RETURNS NULL
                           } catch (ParseException e) {
                               e.printStackTrace();
                           }

I expect the code to return Date, but it returns NULL. Thanks.

Naveen
  • 23
  • 1
  • 3
  • This code may help SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy"); Date d = dateFormat.parse(datestring) – AmeeJoshi Jun 14 '19 at 07:43

1 Answers1

0

Debug value of your dateYou need to provide the format in which you are receiving date from firebase . In order to convert string to date use the below function :

public static Date getDateFromString(String dateText, String fromFormat) {
    Date date = new Date();
    SimpleDateFormat dateFormat = new SimpleDateFormat(fromFormat, Locale.getDefault());
    try {
        date = dateFormat.parse(dateText);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return date;
}

Just make sure you are passing the correct date format .

Mini Chip
  • 949
  • 10
  • 12