I use Material design to implement Date Picker but I need to disabled the user select some specific dates how I can implement this ?
Below is my code:
button=findViewById(R.id.select_date);
Calendar calendar=Calendar.getInstance(TimeZone.getTimeZone("UTC"));
calendar.clear();
long today=MaterialDatePicker.todayInUtcMilliseconds();
CalendarConstraints.Builder cons=new CalendarConstraints.Builder();
cons.setValidator(DateValidatorPointForward.now());
MaterialDatePicker.Builder builder=MaterialDatePicker.Builder.datePicker();
builder.setTitleText("Select booking date");
builder.setSelection(today);
builder.setCalendarConstraints(cons.build());
MaterialDatePicker materialDatePicker=builder.build();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
materialDatePicker.show(getSupportFragmentManager(),"Date Picker");
}});
materialDatePicker.addOnPositiveButtonClickListener(new MaterialPickerOnPositiveButtonClickListener() {
#Override
public void onPositiveButtonClick(Object selection) {
System.out.println(materialDatePicker.getHeaderText());
}
});
}
}
The values in this Calendar[] are explicitly disabled (not selectable). This option can be used together with setSelectableDays(Calendar[] days): in case there is a clash setDisabledDays(Calendar[] days) will take precedence over setSelectableDays(Calendar[] days)
String[] holidays = {"07-03-2018","05-03-2018","10-03-2018"};
java.util.Date date = null;
for (int i = 0;i < holidays.length; i++) {
try {
date = sdf.parse(holidays[i]);
} catch (ParseException e) {
e.printStackTrace();
}
calendar = dateToCalendar(date);
System.out.println(calendar.getTime());
List<Calendar> dates = new ArrayList<>();
dates.add(calendar);
Calendar[] disabledDays1 = dates.toArray(new Calendar[dates.size()]);
dpd.setDisabledDays(disabledDays1);
}
private Calendar dateToCalendar(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar;
}
Related
I want change the month and year with these two numberpickers but I do not know how to change the date. What I want to do is this: when i click on OK button on BottomSheetDialog I want to set the month and year. Can you help me please? I tried but I couldn't find any solution on the internet. If you help me, I'll be appreciated. Thank you.
public class PlannerFragment extends Fragment implements CalendarAdapter.OnItemListener{
private TextView monthYearTextView;
private TextView monthYearPickerOKTextView;
private ImageView nextMonthImageView, previousMonthImageView;
private RecyclerView calendarRecyclerView;
private LocalDate selectedDate; /// tekrar buna bakılacak
private NumberPicker monthNumberPicker, yearNumberPicker;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
getActivity().setTitle("Planner");
View v = inflater.inflate(R.layout.fragment_planner, container, false);
previousMonthImageView = v.findViewById(R.id.previous_month_image_view);
nextMonthImageView = v.findViewById(R.id.next_month_image_view);
calendarRecyclerView = v.findViewById(R.id.calendar_recycler_view);
monthYearTextView = v.findViewById(R.id.month_year_text_view);
selectedDate = LocalDate.now();
setMonthYear();
previousMonthImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectedDate = selectedDate.minusMonths(1);
setMonthYear();
}
});
nextMonthImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectedDate = selectedDate.plusMonths(1);
setMonthYear();
}
});
monthYearTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
monthYearPicker(v);
}
});
return v;
}
private void setMonthYear() {
monthYearTextView.setText(monthYearFromDate(selectedDate));
ArrayList<String> daysInMonth = daysInMonthArray(selectedDate);
CalendarAdapter calendarAdapter = new CalendarAdapter(getActivity(), daysInMonth,
this);
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getActivity(), 7);
calendarRecyclerView.setLayoutManager(layoutManager);
calendarRecyclerView.setAdapter(calendarAdapter);
}
private ArrayList<String> daysInMonthArray(LocalDate date) {
ArrayList<String> daysInMonthList = new ArrayList<>();
YearMonth yearMonth = YearMonth.from(date);
int daysInMonth = yearMonth.lengthOfMonth();
LocalDate firstDayOfMonth = selectedDate.withDayOfMonth(1);
int dayOfWeek = firstDayOfMonth.getDayOfWeek().getValue();
if (dayOfWeek == 7){
dayOfWeek = 1;
} else {
dayOfWeek++;
}
for (int i = 1; i <= 42; i++) {
if (i < dayOfWeek || i >= daysInMonth + dayOfWeek){
daysInMonthList.add("");
} else {
daysInMonthList.add(String.valueOf(i - dayOfWeek + 1));
}
}
return daysInMonthList;
}
private String monthYearFromDate(LocalDate localDate) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM yyyy");
return localDate.format(formatter);
}
#Override
public void onItemClick(int position, String dayText) {
LocalDate firstDayOfMonth = selectedDate.withDayOfMonth(1);
int dayOfWeek = firstDayOfMonth.getDayOfWeek().getValue();
if (dayOfWeek == 7){
dayOfWeek = 1;
} else {
dayOfWeek++;
}
if (!dayText.equals("")){
/*Toast.makeText(getActivity(), dayText + " " + monthYearFromDate(selectedDate),
Toast.LENGTH_SHORT).show();*/
Toast.makeText(getActivity(), String.valueOf(dayOfWeek),
Toast.LENGTH_SHORT).show();
}
}
public void monthYearPicker(View v){
BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(getActivity(),
R.style.BottomSheetDialogTheme);
View bottomSheetView = LayoutInflater.from(getActivity())
.inflate(R.layout.month_and_year_picker_bottom_sheet_layout,
(ConstraintLayout) v.findViewById(R.id.month_year_picker_bottom_sheet_container));
monthNumberPicker = bottomSheetView.findViewById(R.id.month_number_picker);
yearNumberPicker = bottomSheetView.findViewById(R.id.year_number_picker);
final Calendar calendar = Calendar.getInstance();
Month.initMonths();
monthNumberPicker.setMinValue(0);
monthNumberPicker.setMaxValue(Month.getMonthArrayList().size() - 1);
monthNumberPicker.setDisplayedValues(Month.monthNames());
monthNumberPicker.setValue(calendar.get(Calendar.MONTH));
yearNumberPicker.setMinValue(1984);
yearNumberPicker.setMaxValue(2040);
yearNumberPicker.setValue(calendar.get(Calendar.YEAR));
bottomSheetView.findViewById(R.id.month_year_picker_ok_text_view).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
bottomSheetDialog.dismiss();
selectedDate.withMonth(monthNumberPicker.getValue());
setMonthYear();
Toast.makeText(getActivity(), Month.getMonthArrayList().get(monthNumberPicker.getValue()).getName(),
Toast.LENGTH_SHORT).show();
}
});
bottomSheetDialog.setContentView(bottomSheetView);
bottomSheetDialog.show();
}
}
Good implementation, proper updated answer:
LocalDate date1 = LocalDate.of(2021, Month.JANUARY, 1);
LocalDate date2 = date1.withYear(2010);
LocalDate date3 = date2.withMonth(Month.DECEMBER.getValue());
LocalDate date4 = date3.withDayOfMonth(15);
LocalDate date5 = date4.with(ChronoField.DAY_OF_YEAR, 100);
Stolen from https://kodejava.org/how-do-i-manipulate-the-value-of-localdate-object/
Bad outdated implementation, bad answer (just here for protocol)
Simple pure Java implementation:
Use Calendar. Create a new instance; you probably want Gregorian Calendar: Calendar.getInstance();
Set the calendar value to the date: cal.setTime(pDate);
adjust single fields: cal.add(pField, pValue); or cal.set(pField, pValue);
retrieve Date object: cal.getTime();
You could also use the new java.time package, with classes like LocalDateTime etc.
And then there's a myriad of Java Date Time libraries out there.
Choose the way that works best for you.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
When click on next button i need to set the next month to text view without opening the month picker and similarly to previous button also. Please can any one help me.
Here is my code
Date today = Calendar.getInstance().getTime();//getting date
SimpleDateFormat formatter = new SimpleDateFormat("MMM-YYYY");
String date = formatter.format(today);
Calendar today1 = Calendar.getInstance();
textView.setText(date);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
String dateString = textView.getText().toString();
SimpleDateFormat sdf = new SimpleDateFormat("MMM-YYYY");
//Date date = sdf.parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
}
});
Get month,year from Calender as String , then parse it as LocalDate then format it through formater .
Example-
public class MainActivity extends AppCompatActivity {
private TextView monthView;
Button next, previous;
public static LocalDate localDate;
private String dateFormat;
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
monthView = findViewById(R.id.tvLDate);
next = findViewById(R.id.next);
previous = findViewById(R.id.previous);
getDate();
next.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onClick(View v) {
localDate = localDate.plusMonths(1);
monthView.setText(monthFormat(localDate));
}
});
previous.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onClick(View v) {
localDate = localDate.minusMonths(1);
monthView.setText(monthFormat(localDate));
}
});
}
#RequiresApi(api = Build.VERSION_CODES.O)
private void getDate() {
Calendar calendar = Calendar.getInstance();
String month = calendar.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.getDefault());
String year = String.valueOf(calendar.get(Calendar.YEAR));
dateFormat = "01/" + month + "/" + year;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MMMM/yyyy");
localDate = LocalDate.parse(dateFormat, formatter);
}
#RequiresApi(api = Build.VERSION_CODES.O)
private String monthFormat(LocalDate date) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM");
return date.format(formatter);
}
}
what you could do is ->
// Get an instance of calendar and set the required Date()
val calendar = Calendar.getInstance()
mButtonNextMonth.setOnClickListener {
calendar[Calendar.MONTH] += 1 // This will give you the currently selected month +1
}
mButtonNextMonth.setOnClickListener {
calendar[Calendar.MONTH] -= 1 // This will give you the currently selected month -1
}
This question already has answers here:
Android calculate days between two dates
(17 answers)
How to get number of days between two calendar instance?
(12 answers)
Closed 2 years ago.
i create a booking hotels apps and it hase 3 textview and 2 button to choose the date. if button click it display a date and selected date will displayed to 2 textview. how to display the day between dates in the third textview??
here's my code ( the third textview not displayed as day between dates)
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dateFormatter = new SimpleDateFormat("dd-MM-yyyy", Locale.US);
tvDateResult = (TextView) findViewById(R.id.tv_dateresult);
res = findViewById(R.id.tv_dateresult1);
ress = findViewById(R.id.tv_dateresult2);
btDatePicker = (Button) findViewById(R.id.bt_datepicker);
date = findViewById(R.id.bt_datepicker1);
get = findViewById(R.id.getprice);
date.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showDateDialog2();
}
});
btDatePicker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showDateDialog();
}
});
}
private void showDateDialog2() {
Calendar newCalendar = Calendar.getInstance();
datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar newDate = Calendar.getInstance();
newDate.set(year, monthOfYear, dayOfMonth);
res.setText(dateFormatter.format(newDate.getTime()));
}
},newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
datePickerDialog.show();
if(tvDateResult !=null || res !=null) {
try {
String a = tvDateResult.getText().toString();
String b = res.getText().toString();
Date aa = dateFormatter.parse(a);
Date bb = dateFormatter.parse(b);
long diff = bb.getTime() - aa.getTime() / 24 * 60 * 60 * 1000;
ress.setText((int) TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));
} catch (ParseException e) {
e.printStackTrace();
}
}
}
private void showDateDialog(){
Calendar newCalendar = Calendar.getInstance();
datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar newDate = Calendar.getInstance();
newDate.set(year, monthOfYear, dayOfMonth);
tvDateResult.setText(dateFormatter.format(newDate.getTime()));
}
},newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
datePickerDialog.show();
}
Declare 2 global variables:
Calendar date1 = null, date2 = null;
In onDateSet method of both date pickers, save the selected date in global variables.
In onDateSet of first date picker,
Calendar newDate = Calendar.getInstance();
date1 = newDate
updateTextView()
Similarly, In onDateSet of second date picker,
Calendar newDate = Calendar.getInstance();
date1 = newDate
updateTextView()
Call a method from both onDateSet methods.
private void updateTextView() {
if(date1 != null && date2 != null) {
tvDateResult .setText(dateFormatter.format(daysBetween(date1,date2)));
}
}
public static long daysBetween(Calendar startDate, Calendar endDate) {
// Make sure we don't change the parameter passed
Calendar newStart = Calendar.getInstance();
newStart.setTimeInMillis(startDate.getTimeInMillis());
newStart.set(Calendar.HOUR_OF_DAY, 0);
newStart.set(Calendar.MINUTE, 0);
newStart.set(Calendar.SECOND, 0);
newStart.set(Calendar.MILLISECOND, 0);
Calendar newEnd = Calendar.getInstance();
newEnd.setTimeInMillis(endDate.getTimeInMillis());
newEnd.set(Calendar.HOUR_OF_DAY, 0);
newEnd.set(Calendar.MINUTE, 0);
newEnd.set(Calendar.SECOND, 0);
newEnd.set(Calendar.MILLISECOND, 0);
long end = newEnd.getTimeInMillis();
long start = newStart.getTimeInMillis();
return TimeUnit.MILLISECONDS.toDays(Math.abs(end - start));
}
Reference: How to get number of days between two calendar instance?
I created buttons for display current time for start and stop parking and its work.
But when I clicked on the deductbtn, the apps on the phone will pop up and show "my Application 1 has stopped"
How can I fix this? Any help will be much appciated.
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_payment_info);
firebaseAuth = FirebaseAuth.getInstance();
parkBtn = (Button)findViewById(R.id.parkBtn);
stopparkBtn = (Button)findViewById(R.id.stopparkBtn);
deductBtn = (Button)findViewById(R.id.deductBtn);
timeResult = (TextView)findViewById(R.id.timeResult);
timeResult2 = (TextView)findViewById(R.id.timeResult2);
diffResult = (TextView)findViewById(R.id.diffResult);
parkBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final Date d = new Date();
SimpleDateFormat sdf1=new SimpleDateFormat("hh:mm a");
final String currentDateTimeString = sdf1.format(d);
timeResult.setText(currentDateTimeString);
}
});
stopparkBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final Date d1= new Date();
SimpleDateFormat sdf2 = new SimpleDateFormat("hh:mm a");
final String currentDateTimeString1 = sdf2.format(d1);
timeResult2.setText(currentDateTimeString1);
}
});
deductBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
float totalTime = Float.parseFloat(timeResult2.getText().toString());
float totalTime1 = Float.parseFloat(timeResult.getText().toString());
final float timeUsage = totalTime - totalTime1;
diffResult.setText(String.valueOf(timeUsage));
}
});
}
}
The new code is here :
#Override
public void onClick(View view) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm a");
Date date1 = null;
try {
date1 = simpleDateFormat.parse(timeResult.getText().toString());
} catch (ParseException e) {
e.printStackTrace();
}
Date date2 = null;
try {
date2 = simpleDateFormat.parse(timeResult2.getText().toString());
} catch (ParseException e) {
e.printStackTrace();
}
String diffResult= DateUtils.getRelativeTimeSpanString(date1.getTime(), date2.getTime(), DateUtils.FORMAT_SHOW_TIME).toString();
deductBtn.setText(diffResult);
}
You are getting exception because
float totalTime = Float.parseFloat(timeResult2.getText().toString());
float totalTime1 = Float.parseFloat(timeResult.getText().toString());
Here, If you click this button after performing click on other buttons, then textview's text will be in the format hh:mm a
And if you click button for the first time without clicking other buttons , The strings will be empty
Both will throw exception
java.lang.NumberFormatException: Invalid float
You can use,
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm a");
date1 = simpleDateFormat.parse(timeResult2.getText().toString());
date2 = simpleDateFormat.parse(timeResult.getText().toString());
String diff= DateUtils.getRelativeTimeSpanString(date1.getTime(), date2.getTime(), DateUtils.HOUR_IN_MILLIS).toString();
Make sure that your textviews strings are not empty before doing it.
Below is my code of Datepicker allowing user to select dates and updates the textview with the selected date. How do I update the textview with an error message when user selects the date before today?
public void startCalender() {
txtTrigger = (TextView) findViewById(R.id.calTrigger);
final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int day) {
myCalendar.set(Calendar.DAY_OF_MONTH, day);
myCalendar.set(Calendar.MONTH, month);
myCalendar.set(Calendar.YEAR, year);
updateLabel();
}
};
txtTrigger.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new DatePickerDialog(DisplayCeeAct.this, date,
myCalendar.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
myCalendar.get(Calendar.DAY_OF_MONTH)).show();
}
});
}
private void updateLabel() {
String no = "<font color='red'>NO</font>.";
String myFormat = "dd/MM/yy";
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.getDefault());
if (myCalendar.after(myCalendar.getTime())){
txtTrigger.setText(sdf.format(myCalendar.getTime()));
}
else {
txtTrigger.setText(Html.fromHtml(no), TextView.BufferType.SPANNABLE);
}
}
Seems this line is crashing:
txtTrigger.setText(Html.fromHtml(no), TextView.BufferType.SPANNABLE);
A better approach would be:
txtTrigger.setText("NO");
txtTrigger.setTextColor(Color.RED);