datepickerLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
final Calendar calendar = Calendar.getInstance();
int yy = calendar.get(Calendar.YEAR);
int mm = calendar.get(Calendar.MONTH);
int dd = calendar.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(getContext(),new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
datePickerDialog.getTouchables().get(0).performClick();
String strdate=year+"-"+(monthOfYear+1)+"-"+dayOfMonth;
}
}, yy, mm, dd);
datePickerDialog.getDatePicker().setMinDate(calendar.getTimeInMillis());
datePickerDialog.show();
}
});
I want to display years in datepicker when button is clicked after selecting the years i want to select date.
You can achieve this simply using below code
DatePickerDialog dialog = new DatePickerDialog(getActivity(), this, year, month, day);
dialog.getDatePicker().getTouchables().get( 0 ).performClick();
Use below class to open dialog
public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
OnDateOfBirthSelection registrationIIFragment;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
DatePickerDialog abc = new DatePickerDialog(getActivity(), this, year, month, day);
//18 Years =568,025,136,000 Milliseconds
double diff = System.currentTimeMillis() - 568025136000.0;
abc.getDatePicker().setMaxDate((long) diff);
abc.getDatePicker().getTouchables().get( 0 ).performClick();
return abc;
}
public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date chosen by the user
// tv1.setText("Year: "+view.getYear()+" Month: "+view.getMonth()+" Day: "+view.getDayOfMonth());
registrationIIFragment.onDateOfBirthSelected(view.getDayOfMonth() + " - " + (view.getMonth() + 1) + " - " + view.getYear());
}
public void setCallbackListener(OnDateOfBirthSelection registrationIIFragment) {
this.registrationIIFragment = registrationIIFragment;
}
public interface OnDateOfBirthSelection {
public void onDateOfBirthSelected(String s);
} }
In button click create above class instance and call show method.
DatePickerFragment newFragment = new DatePickerFragment();
newFragment.setCallbackListener(this);
newFragment.show(getSupportFragmentManager(), "datePicker");
above code will display output as below image
Hope this will help thanks
Related
I am trying to implement this DatePickerDialog in my Android App:
public void showDatePickerDialog(View v) {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getFragmentManager(), "datePicker");
}
public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
int mon = month + 1;
date = day + "/" + mon + "/" + year;
textview1.setText(date);
}
}
unfortunatly the App crashes when I try to show the dialog showDatePickerDialog(imageview1); and I get the following Error:
"DatePickerFragment must be a public static class to be properly recreated from instant state"
May someone please help me fix this? I am grateful for every response :)
I have this code, I want to add 40 weeks to the date I get from the date Picker and get the new date after the 40 weeks (280 days) has been added to the date from the date picker.
Code:
public class MainActivity extends AppCompatActivity {
DatePickerDialog picker;
EditText eText;
Button btnGet;
TextView tvw;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvw=(TextView)findViewById(R.id.textView1);
eText=(EditText) findViewById(R.id.editText1);
eText.setInputType(InputType.TYPE_NULL);
eText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Calendar cldr = Calendar.getInstance();
int day = cldr.get(Calendar.DAY_OF_MONTH);
int month = cldr.get(Calendar.MONTH);
int year = cldr.get(Calendar.YEAR);
// date picker dialog
picker = new DatePickerDialog(MainActivity.this,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
eText.setText(dayOfMonth + "/" + (monthOfYear + 1) + "/" + year);
}
}, year, month, day);
picker.show();
}
});
btnGet=(Button)findViewById(R.id.button1);
btnGet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tvw.setText("Selected Date: "+ eText.getText());
}
});
}
}
Joda time is a very convenient library for handling such cases. Add this to your project:
dependencies {
compile 'joda-time:joda-time:2.10.2'
}
And then you can manipulate the dates like this:
DateTime dt = DateTime.now();
DateTime laterDate = dt.withYear(2020)
.withMonthOfYear(3)
.withDayOfMonth(14)
.plusWeeks(40);
Remember that in JodaTime date objects are immutable (which is a very good idea), so each manipulation produces a new object.
First, convert the current format to milliseconds and then add specific days milliseconds and then again get it in the desired format. Like this way:
new DatePickerDialog(MainActivity.this,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar calendar = Calendar.getInstance();
calendar.set(year,monthOfYear + 1,dayOfMonth);
long timeInMilliseconds =
calendar.getTimeInMillis()+TimeUnit.DAYS.toMillis(280);
calendar.setTimeInMillis(timeInMilliseconds);
int mYear = calendar.get(Calendar.YEAR);
int mMonth = calendar.get(Calendar.MONTH);
int mDay = calendar.get(Calendar.DAY_OF_MONTH);
eText.setText(mDay + "/" + mMonth + "/" + mYear);
}
}, year, month, day);
picker.show();
}
});
Use add(Calendar.DAY_OF_MONTH, int) function in this way:
cldr.add(Calendar.DAY_OF_MONTH, 280);
Logically speaking, you don't have to add 40 weeks per say, a week has specific number of days, thus you can just add 40*7 = 280 days in your current day picked up from date picker.
[current date] + TimeUnit.DAYS.toMillis(280)
Calendar calender = Calendar.getInstance();
final CustomDatePickerDialog pickerDialog = new CustomDatePickerDialog(LabCheckOutActivity.this,
myDateListener, calender.get(Calendar.YEAR), calender.get(Calendar.MONTH),
calender.get(Calendar.DAY_OF_MONTH)+1);
pickerDialog.getDatePicker().setMinDate(System.currentTimeMillis()-1000);
pickerDialog.show();
by Using this code, in dialog date is pointed to tomorrow but user can also select todays date.I want user can select date from tomorrow not today.
public class CustomDatePickerDialog extends DatePickerDialog {
int maxYear;
int maxMonth;
int maxDay;
public CustomDatePickerDialog(Context context, OnDateSetListener callBack, int year, int monthOfYear, int dayOfMonth) {
super(context, callBack, year, monthOfYear, dayOfMonth);
}
public void setMaxDate(long maxDate) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
getDatePicker().setMaxDate(System.currentTimeMillis());
} else {
final Calendar c = Calendar.getInstance();
c.setTimeInMillis(maxDate);
maxYear = c.get(Calendar.YEAR);
maxMonth = c.get(Calendar.MONTH);
maxDay = c.get(Calendar.DAY_OF_MONTH);
}
}
#Override
public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
super.onDateChanged(view, year, monthOfYear, dayOfMonth);
} else {
if (year > maxYear)
view.updateDate(maxYear, maxMonth, maxDay);
if (monthOfYear > maxMonth && year == maxYear)
view.updateDate(maxYear, maxMonth, maxDay);
if (dayOfMonth > maxDay && year == maxYear && monthOfYear == maxMonth)
view.updateDate(maxYear, maxMonth, maxDay);
}
}
}
Use
pickerDialog.getDatePicker().setMinDate(System.currentTimeMillis()+24*60*60*1000);//where 24*60*60*1000 represents the total timestamp for one day
instead of
pickerDialog.getDatePicker().setMinDate(System.currentTimeMillis()-1000);
Please see complete implementation below:
DialogFragment class
public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener
{
public DatePickerFragment()
{
}
public void setiDateTimeListener(IDateTimeListener iDateTimeListener)
{
this.iDateTimeListener = iDateTimeListener;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(), this, year, month, day);
// Set minimum date as tommorw
datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis() + 24*60*60*1000);
// If need to set max date then use this also
// datePickerDialog.getDatePicker().setMaxDate(System.currentTimeMillis());
// Create a new instance of DatePickerDialog and return it
return datePickerDialog;
}
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
{
try
{
String selectedDt = dayOfMonth+"-"+(monthOfYear + 1)+"-"+year;
iDateTimeListener.onDateSet(selectedDt);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Interface must be implemented in date picker calling class
public interface IDateTimeListener
{
public void onDateSet(String date);
}
Calling dialog fragment
public void showDatePickerDialog()
{
DatePickerFragment datePickerFragment = new DatePickerFragment();
datePickerFragment.setiDateTimeListener(this);
datePickerFragment.show(getActivity().getSupportFragmentManager(),"datePicker");
}
if (CustomVerticalCalendarView.isPreviousDateDisabled()) { // disable previous date disable flow
int daysOfYear = listCalender.get(Calendar.DAY_OF_YEAR);
int currentDate = today.get(Calendar.DAY_OF_YEAR);
int listYear = listCalender.get(Calendar.YEAR);
int currentYear = today.get(Calendar.YEAR);
if (daysOfYear < currentDate || listYear < currentYear) {
checkBox.setEnabled(false);
checkBox.setTextColor(ContextCompat.getColor(checkBox.getContext(), R.color.dark_gray));
}
}
Hope this code helps you.
I want to use the calendarDaysBetween() below method in my TextView, or I want my TextView to display difference of two dates. Can anyone help me with this?
public class MainActivity extends FragmentActivity {
static EditText metTodate, metFromdate, metInTime, metOutTime;
static long no_of_days1;
static long no_of_days2;
Button mbtnApplyLeave;
ImageView mivBack;
RadioButton halfday1, halfday2, first_half, second_half, first_half1, second_half1, full_day1, full_day2;
static TextView no_of_days;
static TextView no_of_days3;
public static String str;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
metTodate = (EditText)findViewById(R.id.etTodate);
metFromdate = (EditText)findViewById(R.id.etFromdate);
metInTime = (EditText)findViewById(R.id.etInTime);
metOutTime = (EditText)findViewById(R.id.etOutTime);
mivBack = (ImageView)findViewById(R.id.ivBack);
halfday1 = (RadioButton)findViewById(R.id.halfday1);
halfday2 = (RadioButton)findViewById(R.id.halfday2);
first_half = (RadioButton)findViewById(R.id.firsthalf1);
second_half = (RadioButton)findViewById(R.id.secondhalf1);
first_half1 = (RadioButton)findViewById(R.id.firsthalf2);
second_half1 = (RadioButton)findViewById(R.id.secondhalf2);
full_day1 = (RadioButton)findViewById(R.id.fullday1);
full_day2 = (RadioButton)findViewById(R.id.fullday2);
no_of_days = (TextView)findViewById(R.id.etnoofdays);
// Here is my method where I want my text view to display dates.
no_of_days.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
calendarDaysBetween(Calendar metFromdate, Calendar metTodate);
}
});
}
// Both date picker dialogs
public void showTruitonDatePickerDialog(View v) {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");
}
public static class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date chosen by the user
metTodate.setText(day + "/" + (month + 1) + "/" + year);
}
}
public void showFromDatePickerDialog(View v) {
DialogFragment newFragment = new FromDatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");
}
public static class FromDatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c1 = Calendar.getInstance();
int year = c1.get(Calendar.YEAR);
int month = c1.get(Calendar.MONTH);
int day1 = c1.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day1);
// calendarDaysBetween(Calendar metFromdate, Calendar metTodate);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date chosen by the user
metFromdate.setText(day + "/" + (month + 1) + "/" + year);
}
}
public static long calendarDaysBetween(Calendar metFromdate, Calendar metTodate) {
// Create copies so we don't update the original calendars.
Calendar start = Calendar.getInstance();
start.setTimeZone(metFromdate.getTimeZone());
start.setTimeInMillis(metFromdate.getTimeInMillis());
Calendar end = Calendar.getInstance();
end.setTimeZone(metTodate.getTimeZone());
end.setTimeInMillis(metTodate.getTimeInMillis());
// Set the copies to be at midnight, but keep the day information.
start.set(Calendar.HOUR_OF_DAY, 0);
start.set(Calendar.MINUTE, 0);
start.set(Calendar.SECOND, 0);
start.set(Calendar.MILLISECOND, 0);
end.set(Calendar.HOUR_OF_DAY, 0);
end.set(Calendar.MINUTE, 0);
end.set(Calendar.SECOND, 0);
end.set(Calendar.MILLISECOND, 0);
// At this point, each calendar is set to midnight on
// their respective days. Now use TimeUnit.MILLISECONDS to
// compute the number of full days between the two of them.
no_of_days1 = TimeUnit.MILLISECONDS.toDays(Math.abs(end.getTimeInMillis() - start.getTimeInMillis()));
String finalresult = new Double(no_of_days1).toString();
no_of_days.setText(finalresult);
return no_of_days1;
}
}
try this
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Date past = format.parse("05/06/2015");
Date now = new Date();
System.out.println(TimeUnit.MILLISECONDS.toMinutes(now.getTime() - past.getTime()) + " minutes ago");
System.out.println(TimeUnit.MILLISECONDS.toHours(now.getTime() - past.getTime()) + " hours ago");
System.out.println(TimeUnit.MILLISECONDS.toDays(now.getTime() - past.getTime()) + " days ago");
It will give you difference in minute and hours also from current date, you can use your own date format and own date objects
You can use the following code to get a date difference in number of days.
public void calendarDaysBetween(Calendar metFromdate, Calendar etTodate)
{
long diff = (metFromdate.getTimeInMillis() - metTodate.getTimeInMillis());
long no_of_days1 = Math.abs(TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));
no_of_days.setText(no_of_days1+"");
}
First declear Calendar object
public Calendar metFromdate= Calendar.getInstance();
public Calendar metTodate== Calendar.getInstance();
Change first DatePicker values
public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date chosen by the user
metFromdate.set(Calendar.YEAR, year);
metFromdate.set(Calendar.MONTH, month);
metFromdate.set(Calendar.DAY_OF_MONTH, day);
}
change second DatePicker values
public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date chosen by the user
metTodate.set(Calendar.YEAR, year);
metTodate.set(Calendar.MONTH, month);
metTodate.set(Calendar.DAY_OF_MONTH, day);
}
change button click
no_of_days.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
calendarDaysBetween(metFromdate, metTodate);
}
});
you used it
Calendar date1 = Calendar.getInstance(); Calendar date2 =
Calendar.getInstance();
date1.clear();
date1.set(datePicker1.getYear(),datePicker1.getMonth(),datePicker1.getDayOfMonth());
date2.clear();
date2.set(datePicker2.getYear(),datePicker2.getMonth(),datePicker2.getDayOfMonth());
long diff = date2.getTimeInMillis() - date1.getTimeInMillis();
float dayCount = (float) diff / (24 * 60 * 60 * 1000);
textView.setText(Long.toString(diff) + " " + (int) dayCount);
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
........
........
compile 'joda-time:joda-time:2.2'
}
and
public String getTimeAgo(long ago){
DateTime timeAgo = new DateTime(ago*1000L);
DateTime now = new DateTime();
Period period = new Period(timeAgo, now);
PeriodFormatter formatter = new PeriodFormatterBuilder()
.appendYears().appendSuffix(" Years, ")
.appendMonths().appendSuffix(" Months, ")
.appendWeeks().appendSuffix(" Weeks, ")
.appendDays().appendSuffix(" Days, ")
.appendHours().appendSuffix(" Hours, ")
.appendMinutes().appendSuffix(" Minutes, ")
.appendSeconds().appendSuffix(" Seconds ago ")
.printZeroNever()
.toFormatter();
String elapsed = formatter.print(period);
return elapsed;
}
and
yourTextView.setText(getTimeAgo(long-your_past_date_millis));
I have created datePicker dialog in Java file. This is a code:
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
//return new DatePickerDialog(getActivity(), (EditSessionActivity)getActivity(), year, month, day);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
mDateDisplay .setText(String.valueOf(day) + "/"
+ String.valueOf(month + 1) + "/" + String.valueOf(year));
// set selected date into datepicker also
}
}
I want to add ID to my DatePicker. How can I do it from Java file.
Check it:
static final int DATE_DIALOG_ID = 999;
showDialog(DATE_DIALOG_ID);
override the following:
protected Dialog onCreateDialog(int id) {
Calendar c = Calendar.getInstance();
int cyear = c.get(Calendar.YEAR);
int cmonth = c.get(Calendar.MONTH);
int cday = c.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(this, mDateSetListener, cyear, cmonth, cday);
}
Also I need a Listner:
private DatePickerDialog.OnDateSetListener datePickerListener
= new DatePickerDialog.OnDateSetListener() {
// when dialog box is closed, below method will be called.
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
year = selectedYear;
month = selectedMonth;
day = selectedDay;
//set selected date into textview
tvDisplayDate.setText(new StringBuilder().append(month + 1)
.append("-").append(day).append("-").append(year)
.append(" "));
// set selected date into datepicker also
dpResult.init(year, month, day, null);
}
};
Its always good to take a look at android API reference. Take a look at this and this
Anyway as an answer you can do the following
DatePicker picker=datePickerDialog.getDatePicker();
picker.setId("picker");