Solution 1 :
You simply have to use a DateFormatter
class. There are default formats. You just instantiate it, then call format
on it, passing the Date
.
Here is the documentation: DateFormatter.
Dates in Android are a special drag because war broke out between Oracle and Google about the Java licensing terms. So Java was not updated for a while, including Java 8 which included a complete rewrite of dates and times. You can now use Java 8 Dates/Times in Android but if you do you lose compatability with older OSes.
Here is your code, with the formatter added:
public void onPositiveButtonClick(Pair<Long, Long> selection) {
tv1.setText(materialDatePicker.getHeaderText());
startDate = selection.first;
endDate = selection.second;
DateFormatter formatter = SimpleDateFormatter("dd-MM-yyyy", Locale.US);
System.out.println("this is start date: " + formatter.format(startDate));
System.out.println("this is end date " + formatter.format(endDate)));
}
Of course you could use the default Locale.
Problem :
what I should do if i want to print these dates? Because using System.out.println(startDate); System.out.println(endDate); gives me this output : 1595203200000 1596153600000 and I want date as output
public class MainActivity extends AppCompatActivity {
private Button bt1;
private TextView tv1;
private Long startDate;
private Long endDate;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt1 = findViewById(R.id.bt1);
tv1 = findViewById(R.id.tv1);
MaterialDatePicker.Builder<Pair<Long, Long>> builder = MaterialDatePicker.Builder.dateRangePicker();
final MaterialDatePicker<Pair<Long,Long>> materialDatePicker = builder.build();
bt1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
materialDatePicker.show(getSupportFragmentManager(),"date picker");
}
});
/*materialDatePicker.addOnPositiveButtonClickListener(new MaterialPickerOnPositiveButtonClickListener() {
@Override
public void onPositiveButtonClick(Object selection) {
tv1.setText(materialDatePicker.getHeaderText());
}
});*/
materialDatePicker.addOnPositiveButtonClickListener(new MaterialPickerOnPositiveButtonClickListener<Pair<Long, Long>>() {
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
public void onPositiveButtonClick(Pair<Long, Long> selection) {
tv1.setText(materialDatePicker.getHeaderText());
startDate = selection.first;
endDate = selection.second;
System.out.println("this is start date: " + startDate);
System.out.println("this is end date " + endDate);
}
});
}
}
the current output is : I/System.out: this is start date: 1594598400000 this is end date 1596672000000
Comments
Comment posted by priks
Can you please share the code line for this as I am facing some problem while writting these.
Comment posted by Rob
@priks example is there