Better method to retrieve date and time from Datepicker and Timepicker and then convert it to milliseconds












0














I currently have an android Activity that allows the users to select the startDate, endDate, startTime and endTime. Once they click the "submit" button, I will combine the startDate and startTime together, and then convert it to milliseconds. The milliseconds will then be used to set an alarm using the AlarmManager. So far, I was able to convert the startDate and startTime to milliseconds. However, I feel that there are far better solutions out there, which I am not aware of. Below is the screenshot of my layout and my java code



enter image description here



MainActivity



public class MainActivity extends AppCompatActivity implements DatePickerDialog.OnDateSetListener,
TimePickerDialog.OnTimeSetListener, View.OnClickListener {

private TextView txtStartDate;
private TextView txtEndDate;
private TextView txtStartTime;
private TextView txtEndTime;
private Button btnSubmit;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

txtStartDate = findViewById(R.id.txtStartDate);
txtEndDate = findViewById(R.id.txtEndDate);
txtStartTime = findViewById(R.id.txtStartTime);
txtEndTime = findViewById(R.id.txtEndTime);
btnSubmit = findViewById(R.id.btnSubmit);

txtStartDate.setOnClickListener(this);
txtEndDate.setOnClickListener(this);
txtStartTime.setOnClickListener(this);
txtEndTime.setOnClickListener(this);
btnSubmit.setOnClickListener(this);

}

@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.txtStartDate:
/* You need to define a unique tag name for each fragment */
createDialogFragment("StartDatePicker");
break;
case R.id.txtEndDate:
createDialogFragment("EndDatePicker");
break;
case R.id.txtStartTime:
createDialogFragment("StartTimePicker");
break;
case R.id.txtEndTime:
createDialogFragment("EndTimePicker");
break;
case R.id.btnSubmit:
retrieveInput();
}
}

private void createDialogFragment(String tag) {
/* getSupportFragmentManager() will return a FragmentManager
* that is used to manage the fragments */
if (tag.equals("StartDatePicker") || tag.equals("EndDatePicker")) {
DialogFragment datePicker = new DatePickerFragment();
datePicker.show(getSupportFragmentManager(), tag);
} else {
DialogFragment timePicker = new TimePickerFragment();
timePicker.show(getSupportFragmentManager(), tag);
}
}

@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
c.set(Calendar.DAY_OF_MONTH, dayOfMonth);

String currentDateString = DateFormat.getDateInstance(DateFormat.FULL).format(c.getTime());

FragmentManager fragmentManager = getSupportFragmentManager();
if (fragmentManager.findFragmentByTag("StartDatePicker") != null) {
txtStartDate.setText(currentDateString);
} else {
txtEndDate.setText(currentDateString);
}
}

@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, hourOfDay);
c.set(Calendar.MINUTE, minute);

String currentTimeString = DateFormat.getTimeInstance(DateFormat.SHORT).format(c.getTime());

FragmentManager fragmentManager = getSupportFragmentManager();
if (fragmentManager.findFragmentByTag("StartTimePicker") != null) {
txtStartTime.setText(currentTimeString);
} else {
txtEndTime.setText(currentTimeString);
}
}

private void retrieveInput() {
/* Get the startDate and startTime and covert it to milliseconds */
String date = txtStartDate.getText().toString();
String time = txtStartTime.getText().toString();
String datetime = date + " " + time;
SimpleDateFormat df = new SimpleDateFormat("EEEE, MMMM d, yyyy hh:mm a");
Date date1 = null;
long milli = 0;
try {
date1 = df.parse(datetime);
milli = date1.getTime();

} catch (ParseException e) {
e.printStackTrace();
}
Toast.makeText(this, "" + milli, Toast.LENGTH_SHORT).show();
}
}


activity_main.xml



<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
tools:layout_editor_absoluteY="81dp">

<TextView
android:id="@+id/txtStartDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="48dp"
android:layout_marginLeft="48dp"
android:layout_marginTop="136dp"
android:text="Start Date"
android:textSize="16sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<TextView
android:id="@+id/txtEndDate"
android:layout_width="wrap_content"
android:layout_height="27dp"
android:layout_marginStart="48dp"
android:layout_marginLeft="48dp"
android:layout_marginTop="36dp"
android:text="EndDate"
android:textSize="16sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/txtStartDate" />

<TextView
android:id="@+id/txtStartTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="136dp"
android:layout_marginEnd="56dp"
android:layout_marginRight="56dp"
android:text="Start Time"
android:textSize="16sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<TextView
android:id="@+id/txtEndTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:layout_marginEnd="60dp"
android:layout_marginRight="60dp"
android:text="End Time"
android:textSize="16sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="@+id/txtStartTime" />

<Button
android:id="@+id/btnSubmit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="192dp"
android:text="Submit"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />




DatePickerFragment.java



public class DatePickerFragment extends DialogFragment {

@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
// Get the current time and use it as the default values for the picker
Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);

// Create and return an instance of the DatePickerDialog
return new DatePickerDialog(getActivity(),
(DatePickerDialog.OnDateSetListener) getActivity(),
year, month, day);


TimePickerFragment.java



public class TimePickerFragment extends DialogFragment {

@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);

return new TimePickerDialog(getActivity(),
(TimePickerDialog.OnTimeSetListener) getActivity(),
hour, minute, DateFormat.is24HourFormat(getActivity()));
}
}









share|improve this question







New contributor




Issaki is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

























    0














    I currently have an android Activity that allows the users to select the startDate, endDate, startTime and endTime. Once they click the "submit" button, I will combine the startDate and startTime together, and then convert it to milliseconds. The milliseconds will then be used to set an alarm using the AlarmManager. So far, I was able to convert the startDate and startTime to milliseconds. However, I feel that there are far better solutions out there, which I am not aware of. Below is the screenshot of my layout and my java code



    enter image description here



    MainActivity



    public class MainActivity extends AppCompatActivity implements DatePickerDialog.OnDateSetListener,
    TimePickerDialog.OnTimeSetListener, View.OnClickListener {

    private TextView txtStartDate;
    private TextView txtEndDate;
    private TextView txtStartTime;
    private TextView txtEndTime;
    private Button btnSubmit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    txtStartDate = findViewById(R.id.txtStartDate);
    txtEndDate = findViewById(R.id.txtEndDate);
    txtStartTime = findViewById(R.id.txtStartTime);
    txtEndTime = findViewById(R.id.txtEndTime);
    btnSubmit = findViewById(R.id.btnSubmit);

    txtStartDate.setOnClickListener(this);
    txtEndDate.setOnClickListener(this);
    txtStartTime.setOnClickListener(this);
    txtEndTime.setOnClickListener(this);
    btnSubmit.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
    switch (v.getId()) {
    case R.id.txtStartDate:
    /* You need to define a unique tag name for each fragment */
    createDialogFragment("StartDatePicker");
    break;
    case R.id.txtEndDate:
    createDialogFragment("EndDatePicker");
    break;
    case R.id.txtStartTime:
    createDialogFragment("StartTimePicker");
    break;
    case R.id.txtEndTime:
    createDialogFragment("EndTimePicker");
    break;
    case R.id.btnSubmit:
    retrieveInput();
    }
    }

    private void createDialogFragment(String tag) {
    /* getSupportFragmentManager() will return a FragmentManager
    * that is used to manage the fragments */
    if (tag.equals("StartDatePicker") || tag.equals("EndDatePicker")) {
    DialogFragment datePicker = new DatePickerFragment();
    datePicker.show(getSupportFragmentManager(), tag);
    } else {
    DialogFragment timePicker = new TimePickerFragment();
    timePicker.show(getSupportFragmentManager(), tag);
    }
    }

    @Override
    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
    Calendar c = Calendar.getInstance();
    c.set(Calendar.YEAR, year);
    c.set(Calendar.MONTH, month);
    c.set(Calendar.DAY_OF_MONTH, dayOfMonth);

    String currentDateString = DateFormat.getDateInstance(DateFormat.FULL).format(c.getTime());

    FragmentManager fragmentManager = getSupportFragmentManager();
    if (fragmentManager.findFragmentByTag("StartDatePicker") != null) {
    txtStartDate.setText(currentDateString);
    } else {
    txtEndDate.setText(currentDateString);
    }
    }

    @Override
    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
    Calendar c = Calendar.getInstance();
    c.set(Calendar.HOUR_OF_DAY, hourOfDay);
    c.set(Calendar.MINUTE, minute);

    String currentTimeString = DateFormat.getTimeInstance(DateFormat.SHORT).format(c.getTime());

    FragmentManager fragmentManager = getSupportFragmentManager();
    if (fragmentManager.findFragmentByTag("StartTimePicker") != null) {
    txtStartTime.setText(currentTimeString);
    } else {
    txtEndTime.setText(currentTimeString);
    }
    }

    private void retrieveInput() {
    /* Get the startDate and startTime and covert it to milliseconds */
    String date = txtStartDate.getText().toString();
    String time = txtStartTime.getText().toString();
    String datetime = date + " " + time;
    SimpleDateFormat df = new SimpleDateFormat("EEEE, MMMM d, yyyy hh:mm a");
    Date date1 = null;
    long milli = 0;
    try {
    date1 = df.parse(datetime);
    milli = date1.getTime();

    } catch (ParseException e) {
    e.printStackTrace();
    }
    Toast.makeText(this, "" + milli, Toast.LENGTH_SHORT).show();
    }
    }


    activity_main.xml



    <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    tools:layout_editor_absoluteY="81dp">

    <TextView
    android:id="@+id/txtStartDate"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="48dp"
    android:layout_marginLeft="48dp"
    android:layout_marginTop="136dp"
    android:text="Start Date"
    android:textSize="16sp"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

    <TextView
    android:id="@+id/txtEndDate"
    android:layout_width="wrap_content"
    android:layout_height="27dp"
    android:layout_marginStart="48dp"
    android:layout_marginLeft="48dp"
    android:layout_marginTop="36dp"
    android:text="EndDate"
    android:textSize="16sp"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/txtStartDate" />

    <TextView
    android:id="@+id/txtStartTime"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="136dp"
    android:layout_marginEnd="56dp"
    android:layout_marginRight="56dp"
    android:text="Start Time"
    android:textSize="16sp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

    <TextView
    android:id="@+id/txtEndTime"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="40dp"
    android:layout_marginEnd="60dp"
    android:layout_marginRight="60dp"
    android:text="End Time"
    android:textSize="16sp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/txtStartTime" />

    <Button
    android:id="@+id/btnSubmit"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginBottom="192dp"
    android:text="Submit"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent" />




    DatePickerFragment.java



    public class DatePickerFragment extends DialogFragment {

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
    // Get the current time and use it as the default values for the picker
    Calendar c = Calendar.getInstance();
    int year = c.get(Calendar.YEAR);
    int month = c.get(Calendar.MONTH);
    int day = c.get(Calendar.DAY_OF_MONTH);
    int hour = c.get(Calendar.HOUR_OF_DAY);
    int minute = c.get(Calendar.MINUTE);

    // Create and return an instance of the DatePickerDialog
    return new DatePickerDialog(getActivity(),
    (DatePickerDialog.OnDateSetListener) getActivity(),
    year, month, day);


    TimePickerFragment.java



    public class TimePickerFragment extends DialogFragment {

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
    Calendar c = Calendar.getInstance();
    int hour = c.get(Calendar.HOUR_OF_DAY);
    int minute = c.get(Calendar.MINUTE);

    return new TimePickerDialog(getActivity(),
    (TimePickerDialog.OnTimeSetListener) getActivity(),
    hour, minute, DateFormat.is24HourFormat(getActivity()));
    }
    }









    share|improve this question







    New contributor




    Issaki is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.























      0












      0








      0







      I currently have an android Activity that allows the users to select the startDate, endDate, startTime and endTime. Once they click the "submit" button, I will combine the startDate and startTime together, and then convert it to milliseconds. The milliseconds will then be used to set an alarm using the AlarmManager. So far, I was able to convert the startDate and startTime to milliseconds. However, I feel that there are far better solutions out there, which I am not aware of. Below is the screenshot of my layout and my java code



      enter image description here



      MainActivity



      public class MainActivity extends AppCompatActivity implements DatePickerDialog.OnDateSetListener,
      TimePickerDialog.OnTimeSetListener, View.OnClickListener {

      private TextView txtStartDate;
      private TextView txtEndDate;
      private TextView txtStartTime;
      private TextView txtEndTime;
      private Button btnSubmit;

      @Override
      protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      txtStartDate = findViewById(R.id.txtStartDate);
      txtEndDate = findViewById(R.id.txtEndDate);
      txtStartTime = findViewById(R.id.txtStartTime);
      txtEndTime = findViewById(R.id.txtEndTime);
      btnSubmit = findViewById(R.id.btnSubmit);

      txtStartDate.setOnClickListener(this);
      txtEndDate.setOnClickListener(this);
      txtStartTime.setOnClickListener(this);
      txtEndTime.setOnClickListener(this);
      btnSubmit.setOnClickListener(this);

      }

      @Override
      public void onClick(View v) {
      switch (v.getId()) {
      case R.id.txtStartDate:
      /* You need to define a unique tag name for each fragment */
      createDialogFragment("StartDatePicker");
      break;
      case R.id.txtEndDate:
      createDialogFragment("EndDatePicker");
      break;
      case R.id.txtStartTime:
      createDialogFragment("StartTimePicker");
      break;
      case R.id.txtEndTime:
      createDialogFragment("EndTimePicker");
      break;
      case R.id.btnSubmit:
      retrieveInput();
      }
      }

      private void createDialogFragment(String tag) {
      /* getSupportFragmentManager() will return a FragmentManager
      * that is used to manage the fragments */
      if (tag.equals("StartDatePicker") || tag.equals("EndDatePicker")) {
      DialogFragment datePicker = new DatePickerFragment();
      datePicker.show(getSupportFragmentManager(), tag);
      } else {
      DialogFragment timePicker = new TimePickerFragment();
      timePicker.show(getSupportFragmentManager(), tag);
      }
      }

      @Override
      public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
      Calendar c = Calendar.getInstance();
      c.set(Calendar.YEAR, year);
      c.set(Calendar.MONTH, month);
      c.set(Calendar.DAY_OF_MONTH, dayOfMonth);

      String currentDateString = DateFormat.getDateInstance(DateFormat.FULL).format(c.getTime());

      FragmentManager fragmentManager = getSupportFragmentManager();
      if (fragmentManager.findFragmentByTag("StartDatePicker") != null) {
      txtStartDate.setText(currentDateString);
      } else {
      txtEndDate.setText(currentDateString);
      }
      }

      @Override
      public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
      Calendar c = Calendar.getInstance();
      c.set(Calendar.HOUR_OF_DAY, hourOfDay);
      c.set(Calendar.MINUTE, minute);

      String currentTimeString = DateFormat.getTimeInstance(DateFormat.SHORT).format(c.getTime());

      FragmentManager fragmentManager = getSupportFragmentManager();
      if (fragmentManager.findFragmentByTag("StartTimePicker") != null) {
      txtStartTime.setText(currentTimeString);
      } else {
      txtEndTime.setText(currentTimeString);
      }
      }

      private void retrieveInput() {
      /* Get the startDate and startTime and covert it to milliseconds */
      String date = txtStartDate.getText().toString();
      String time = txtStartTime.getText().toString();
      String datetime = date + " " + time;
      SimpleDateFormat df = new SimpleDateFormat("EEEE, MMMM d, yyyy hh:mm a");
      Date date1 = null;
      long milli = 0;
      try {
      date1 = df.parse(datetime);
      milli = date1.getTime();

      } catch (ParseException e) {
      e.printStackTrace();
      }
      Toast.makeText(this, "" + milli, Toast.LENGTH_SHORT).show();
      }
      }


      activity_main.xml



      <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto"
      xmlns:tools="http://schemas.android.com/tools"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      tools:context=".MainActivity"
      tools:layout_editor_absoluteY="81dp">

      <TextView
      android:id="@+id/txtStartDate"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_marginStart="48dp"
      android:layout_marginLeft="48dp"
      android:layout_marginTop="136dp"
      android:text="Start Date"
      android:textSize="16sp"
      app:layout_constraintStart_toStartOf="parent"
      app:layout_constraintTop_toTopOf="parent" />

      <TextView
      android:id="@+id/txtEndDate"
      android:layout_width="wrap_content"
      android:layout_height="27dp"
      android:layout_marginStart="48dp"
      android:layout_marginLeft="48dp"
      android:layout_marginTop="36dp"
      android:text="EndDate"
      android:textSize="16sp"
      app:layout_constraintStart_toStartOf="parent"
      app:layout_constraintTop_toBottomOf="@+id/txtStartDate" />

      <TextView
      android:id="@+id/txtStartTime"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_marginTop="136dp"
      android:layout_marginEnd="56dp"
      android:layout_marginRight="56dp"
      android:text="Start Time"
      android:textSize="16sp"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintTop_toTopOf="parent" />

      <TextView
      android:id="@+id/txtEndTime"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_marginTop="40dp"
      android:layout_marginEnd="60dp"
      android:layout_marginRight="60dp"
      android:text="End Time"
      android:textSize="16sp"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintTop_toBottomOf="@+id/txtStartTime" />

      <Button
      android:id="@+id/btnSubmit"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_marginStart="8dp"
      android:layout_marginLeft="8dp"
      android:layout_marginEnd="8dp"
      android:layout_marginRight="8dp"
      android:layout_marginBottom="192dp"
      android:text="Submit"
      app:layout_constraintBottom_toBottomOf="parent"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintStart_toStartOf="parent" />




      DatePickerFragment.java



      public class DatePickerFragment extends DialogFragment {

      @NonNull
      @Override
      public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
      // Get the current time and use it as the default values for the picker
      Calendar c = Calendar.getInstance();
      int year = c.get(Calendar.YEAR);
      int month = c.get(Calendar.MONTH);
      int day = c.get(Calendar.DAY_OF_MONTH);
      int hour = c.get(Calendar.HOUR_OF_DAY);
      int minute = c.get(Calendar.MINUTE);

      // Create and return an instance of the DatePickerDialog
      return new DatePickerDialog(getActivity(),
      (DatePickerDialog.OnDateSetListener) getActivity(),
      year, month, day);


      TimePickerFragment.java



      public class TimePickerFragment extends DialogFragment {

      @NonNull
      @Override
      public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
      Calendar c = Calendar.getInstance();
      int hour = c.get(Calendar.HOUR_OF_DAY);
      int minute = c.get(Calendar.MINUTE);

      return new TimePickerDialog(getActivity(),
      (TimePickerDialog.OnTimeSetListener) getActivity(),
      hour, minute, DateFormat.is24HourFormat(getActivity()));
      }
      }









      share|improve this question







      New contributor




      Issaki is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      I currently have an android Activity that allows the users to select the startDate, endDate, startTime and endTime. Once they click the "submit" button, I will combine the startDate and startTime together, and then convert it to milliseconds. The milliseconds will then be used to set an alarm using the AlarmManager. So far, I was able to convert the startDate and startTime to milliseconds. However, I feel that there are far better solutions out there, which I am not aware of. Below is the screenshot of my layout and my java code



      enter image description here



      MainActivity



      public class MainActivity extends AppCompatActivity implements DatePickerDialog.OnDateSetListener,
      TimePickerDialog.OnTimeSetListener, View.OnClickListener {

      private TextView txtStartDate;
      private TextView txtEndDate;
      private TextView txtStartTime;
      private TextView txtEndTime;
      private Button btnSubmit;

      @Override
      protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      txtStartDate = findViewById(R.id.txtStartDate);
      txtEndDate = findViewById(R.id.txtEndDate);
      txtStartTime = findViewById(R.id.txtStartTime);
      txtEndTime = findViewById(R.id.txtEndTime);
      btnSubmit = findViewById(R.id.btnSubmit);

      txtStartDate.setOnClickListener(this);
      txtEndDate.setOnClickListener(this);
      txtStartTime.setOnClickListener(this);
      txtEndTime.setOnClickListener(this);
      btnSubmit.setOnClickListener(this);

      }

      @Override
      public void onClick(View v) {
      switch (v.getId()) {
      case R.id.txtStartDate:
      /* You need to define a unique tag name for each fragment */
      createDialogFragment("StartDatePicker");
      break;
      case R.id.txtEndDate:
      createDialogFragment("EndDatePicker");
      break;
      case R.id.txtStartTime:
      createDialogFragment("StartTimePicker");
      break;
      case R.id.txtEndTime:
      createDialogFragment("EndTimePicker");
      break;
      case R.id.btnSubmit:
      retrieveInput();
      }
      }

      private void createDialogFragment(String tag) {
      /* getSupportFragmentManager() will return a FragmentManager
      * that is used to manage the fragments */
      if (tag.equals("StartDatePicker") || tag.equals("EndDatePicker")) {
      DialogFragment datePicker = new DatePickerFragment();
      datePicker.show(getSupportFragmentManager(), tag);
      } else {
      DialogFragment timePicker = new TimePickerFragment();
      timePicker.show(getSupportFragmentManager(), tag);
      }
      }

      @Override
      public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
      Calendar c = Calendar.getInstance();
      c.set(Calendar.YEAR, year);
      c.set(Calendar.MONTH, month);
      c.set(Calendar.DAY_OF_MONTH, dayOfMonth);

      String currentDateString = DateFormat.getDateInstance(DateFormat.FULL).format(c.getTime());

      FragmentManager fragmentManager = getSupportFragmentManager();
      if (fragmentManager.findFragmentByTag("StartDatePicker") != null) {
      txtStartDate.setText(currentDateString);
      } else {
      txtEndDate.setText(currentDateString);
      }
      }

      @Override
      public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
      Calendar c = Calendar.getInstance();
      c.set(Calendar.HOUR_OF_DAY, hourOfDay);
      c.set(Calendar.MINUTE, minute);

      String currentTimeString = DateFormat.getTimeInstance(DateFormat.SHORT).format(c.getTime());

      FragmentManager fragmentManager = getSupportFragmentManager();
      if (fragmentManager.findFragmentByTag("StartTimePicker") != null) {
      txtStartTime.setText(currentTimeString);
      } else {
      txtEndTime.setText(currentTimeString);
      }
      }

      private void retrieveInput() {
      /* Get the startDate and startTime and covert it to milliseconds */
      String date = txtStartDate.getText().toString();
      String time = txtStartTime.getText().toString();
      String datetime = date + " " + time;
      SimpleDateFormat df = new SimpleDateFormat("EEEE, MMMM d, yyyy hh:mm a");
      Date date1 = null;
      long milli = 0;
      try {
      date1 = df.parse(datetime);
      milli = date1.getTime();

      } catch (ParseException e) {
      e.printStackTrace();
      }
      Toast.makeText(this, "" + milli, Toast.LENGTH_SHORT).show();
      }
      }


      activity_main.xml



      <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto"
      xmlns:tools="http://schemas.android.com/tools"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      tools:context=".MainActivity"
      tools:layout_editor_absoluteY="81dp">

      <TextView
      android:id="@+id/txtStartDate"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_marginStart="48dp"
      android:layout_marginLeft="48dp"
      android:layout_marginTop="136dp"
      android:text="Start Date"
      android:textSize="16sp"
      app:layout_constraintStart_toStartOf="parent"
      app:layout_constraintTop_toTopOf="parent" />

      <TextView
      android:id="@+id/txtEndDate"
      android:layout_width="wrap_content"
      android:layout_height="27dp"
      android:layout_marginStart="48dp"
      android:layout_marginLeft="48dp"
      android:layout_marginTop="36dp"
      android:text="EndDate"
      android:textSize="16sp"
      app:layout_constraintStart_toStartOf="parent"
      app:layout_constraintTop_toBottomOf="@+id/txtStartDate" />

      <TextView
      android:id="@+id/txtStartTime"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_marginTop="136dp"
      android:layout_marginEnd="56dp"
      android:layout_marginRight="56dp"
      android:text="Start Time"
      android:textSize="16sp"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintTop_toTopOf="parent" />

      <TextView
      android:id="@+id/txtEndTime"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_marginTop="40dp"
      android:layout_marginEnd="60dp"
      android:layout_marginRight="60dp"
      android:text="End Time"
      android:textSize="16sp"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintTop_toBottomOf="@+id/txtStartTime" />

      <Button
      android:id="@+id/btnSubmit"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_marginStart="8dp"
      android:layout_marginLeft="8dp"
      android:layout_marginEnd="8dp"
      android:layout_marginRight="8dp"
      android:layout_marginBottom="192dp"
      android:text="Submit"
      app:layout_constraintBottom_toBottomOf="parent"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintStart_toStartOf="parent" />




      DatePickerFragment.java



      public class DatePickerFragment extends DialogFragment {

      @NonNull
      @Override
      public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
      // Get the current time and use it as the default values for the picker
      Calendar c = Calendar.getInstance();
      int year = c.get(Calendar.YEAR);
      int month = c.get(Calendar.MONTH);
      int day = c.get(Calendar.DAY_OF_MONTH);
      int hour = c.get(Calendar.HOUR_OF_DAY);
      int minute = c.get(Calendar.MINUTE);

      // Create and return an instance of the DatePickerDialog
      return new DatePickerDialog(getActivity(),
      (DatePickerDialog.OnDateSetListener) getActivity(),
      year, month, day);


      TimePickerFragment.java



      public class TimePickerFragment extends DialogFragment {

      @NonNull
      @Override
      public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
      Calendar c = Calendar.getInstance();
      int hour = c.get(Calendar.HOUR_OF_DAY);
      int minute = c.get(Calendar.MINUTE);

      return new TimePickerDialog(getActivity(),
      (TimePickerDialog.OnTimeSetListener) getActivity(),
      hour, minute, DateFormat.is24HourFormat(getActivity()));
      }
      }






      java datetime android






      share|improve this question







      New contributor




      Issaki is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      share|improve this question







      New contributor




      Issaki is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      share|improve this question




      share|improve this question






      New contributor




      Issaki is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      asked 33 mins ago









      Issaki

      1




      1




      New contributor




      Issaki is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.





      New contributor





      Issaki is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      Issaki is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.



























          active

          oldest

          votes











          Your Answer





          StackExchange.ifUsing("editor", function () {
          return StackExchange.using("mathjaxEditing", function () {
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          });
          });
          }, "mathjax-editing");

          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "196"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });






          Issaki is a new contributor. Be nice, and check out our Code of Conduct.










          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f210739%2fbetter-method-to-retrieve-date-and-time-from-datepicker-and-timepicker-and-then%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown






























          active

          oldest

          votes













          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          Issaki is a new contributor. Be nice, and check out our Code of Conduct.










          draft saved

          draft discarded


















          Issaki is a new contributor. Be nice, and check out our Code of Conduct.













          Issaki is a new contributor. Be nice, and check out our Code of Conduct.












          Issaki is a new contributor. Be nice, and check out our Code of Conduct.
















          Thanks for contributing an answer to Code Review Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          Use MathJax to format equations. MathJax reference.


          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f210739%2fbetter-method-to-retrieve-date-and-time-from-datepicker-and-timepicker-and-then%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Morgemoulin

          Scott Moir

          Souastre