Setting user picked date from DatePicker to Calendar - java

So I need for user to select date from DatePicker Dialog and then when he selects date I want it to be shown on Calendar. For example, if user selects 01/01/2016 I want that date to be shown as some red marked date.
Here's my code:
displayDatumaDodajPisaniIspit = (TextView)dialog. findViewById(R.id.displayDatumaDodajPisaniIspit);
set = (Button)dialog. findViewById(R.id.set);
set.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new DatePickerDialog(HomeScreen.this, listener, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)).show();
}
});
And the listener
DatePickerDialog.OnDateSetListener listener = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
displayDatumaDodajPisaniIspit.setText(dayOfMonth + "/" + (monthOfYear + 1) + "/" + year);
calendarView.setDateSelected();
}
};
I don't have idea how to start with it. Tried with some methods in listener but it didn't work.

You should first convert the chosen date into millis -
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, monthOfYear);
calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
long millis = calendar.getTimeInMillis();
and then set the date in your CalendarView like this -
calendarView.setDate(millis);
As you mentioned you are using MaterialCalendarView, then I guess you can use -
calendarView.setSelectedDate(CalendarDay.from(year,monthOfYear,dayOfMonth));

Related

how to set limit of calendar to some date and increase and decrease date on click of a button to same limit in android

i want create such functionality where user can choose date between today's date to 30 days after today's date so i set max date and min date. and plus i want a functionality where i am having two buttons one to increase date and another to decrease date and from those two buttons also user can choose date between today's date to 30 days after today's date but problem is when someone is clicking on button set max date and min date is not working and in date picker dialog first time it is working fine but next time someone is clicking on calendar it is showing 30 days from that date but i don't want that i want to show today's date and 30 days after that date.
to set max date and min date
try {
pickerDialog = com.wdullaer.materialdatetimepicker.date.DatePickerDialog.newInstance(MainActivity.this,
calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH));
pickerDialog.setMinDate(Calendar.getInstance());
calendar.add(Calendar.DAY_OF_MONTH, 30);
pickerDialog.setMaxDate(calendar);
pickerDialog.show(getFragmentManager(), "Date Picker Dialog");
} catch (Exception e) {
e.printStackTrace();
}
to increase date and decrease date
ivBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
calendarSh.add(Calendar.DAY_OF_MONTH, -1);
formattedDate = simpleDateFormat.format(calendarSh.getTime());
Log.v("PREVIOUS DATE : ", formattedDate);
tvDate.setText(formattedDate);
}
});
ivNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
calendarSh.add(Calendar.DAY_OF_MONTH, +1);
formattedDate = simpleDateFormat.format(calendarSh.getTime());
Log.v("NEXT DATE : ", formattedDate);
tvDate.setText(formattedDate);
ivBack.setEnabled(true);
}
});
There are a couple of issues with your code. First, let's consider the date picker. In your code, you are using some variable calendar, which is initialised externally to your date picker intialisation code. When setting up your date picker, you add 30 days to it - but then you are reusing this variable again next time - so adding another 30 days to it - an so on. Instead you should initialise it internally. The code would be something like this:
try {
Calendar newCalendar = Calendar.getInstance();
pickerDialog = com.wdullaer.materialdatetimepicker.date.DatePickerDialog.newInstance(
MainActivity.this,
newCalendar .get(Calendar.YEAR),
newCalendar .get(Calendar.MONTH),
newCalendar .get(Calendar.DAY_OF_MONTH)
);
pickerDialog.setMinDate(newCalendar);
newCalendar.add(Calendar.DAY_OF_MONTH, 30);
pickerDialog.setMaxDate(newCalendar);
pickerDialog.show(getFragmentManager(), "Date Picker Dialog");
} catch (Exception e) {
e.printStackTrace();
}
Now, when you use buttons to increase/decrease dates, your min/max from the date picker do not apply anymore - you have to check against min/max every time. You code could look something like this:
final Calendar minDate = Calendar.getInstance();
final Calendar.maxDate = Calendar.getInstance();
maxDate.add(Calendar.DAY_OF_MONTH, 30);
ivBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (calendarSh.after(minDate)) {
calendarSh.add(Calendar.DAY_OF_MONTH, -1);
formattedDate = simpleDateFormat.format(calendarSh.getTime());
Log.v("PREVIOUS DATE : ", formattedDate);
tvDate.setText(formattedDate);
}
}
});
ivNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (calendarSh.before(maxDate)) {
calendarSh.add(Calendar.DAY_OF_MONTH, +1);
formattedDate = simpleDateFormat.format(calendarSh.getTime());
Log.v("NEXT DATE : ", formattedDate);
tvDate.setText(formattedDate);
}
}
});

How to get date from Calendar [duplicate]

This question already has answers here:
How do I calculate someone's age in Java?
(28 answers)
Closed 5 years ago.
I have another class which showing calendar to user and setup date in textview. But how to get date (year from here? for calculate how old year user in general).
This is code which I'm using. This is: TextViewDatePicker editTextDatePicker = new TextViewDatePicker implement class which shows calendar for user and setup date in text view. I don't know ho to setup this date for this code: Calendar dateOfYourBirth = new GregorianCalendar();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profile_fragment);
editTextForAge = (TextView) findViewById(R.id.ed_calendar);
Window window = this.getWindow();
TextViewDatePicker editTextDatePicker = new TextViewDatePicker(ProfileGeneral.this, editTextForAge);
Calendar dateOfYourBirth = new GregorianCalendar();
Calendar today = Calendar.getInstance();
int yourAge = today.get(Calendar.YEAR) - dateOfYourBirth.get(Calendar.YEAR);
dateOfYourBirth.add(Calendar.YEAR, yourAge);
if (today.before(dateOfYourBirth)) {
yourAge--;
}
And this is class which showing calendar for user:
public class TextViewDatePicker
implements View.OnClickListener, DatePickerDialog.OnDateSetListener {
public static final String DATE_SERVER_PATTERN = "yyyy-MM-dd";
private DatePickerDialog mDatePickerDialog;
private TextView mView;
private Context mContext;
private long mMinDate;
private long mMaxDate;
public TextViewDatePicker(Context context, TextView view) {
this(context, view, 0, 0);
}
public TextViewDatePicker(Context context, TextView view, long minDate, long maxDate) {
mView = view;
mView.setOnClickListener(this);
mView.setFocusable(false);
mContext = context;
mMinDate = minDate;
mMaxDate = maxDate;
}
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, monthOfYear);
calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
Date date = calendar.getTime();
SimpleDateFormat formatter = new SimpleDateFormat(DATE_SERVER_PATTERN);
mView.setText(formatter.format(date));
}
#Override
public void onClick(View v) {
Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
mDatePickerDialog = new DatePickerDialog(mContext, this, calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
if (mMinDate != 0) {
mDatePickerDialog.getDatePicker().setMinDate(mMinDate);
}
if (mMaxDate != 0) {
mDatePickerDialog.getDatePicker().setMaxDate(mMaxDate);
}
mDatePickerDialog.show();
}
This goes a lot easier with java.time, the modern Java date and time API.
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
// date picker month is 0-based, so add 1 to it
LocalDate datePickerDate = LocalDate.of(year, monthOfYear + 1, dayOfMonth);
mView.setText(datePickerDate.toString());
LocalDate today = LocalDate.now(ZoneId.of("America/Tortola"));
long yourAge = ChronoUnit.YEARS.between(datePickerDate, today);
}
Can you use this on Android? Certainly! For most Android devices you will need to get ThreeTenABP, the backport of java.time from Java 8 to Android Java 7. It is all well explained in this question: How to use ThreeTenABP in Android Project (that is ThreeTen for JSR-310, where java.time wsa first described, and ABP for Android Backport).
Please substitute your desired time zone if it doesn’t happen to be America/Tortola.
You used wrong constructor for TextViewDatePicker
Update code :
TextViewDatePicker editTextDatePicker = new TextViewDatePicker(ProfileGeneral.this, editTextForAge);
with
TextViewDatePicker editTextDatePicker = new TextViewDatePicker(ProfileGeneral.this, editTextForAge,0,0);

Date displaying twice in date picker

Current date is displaying twice in my date picker android app I don't
understand why this is happening.Can anyone tell me what is causing this.
public void onClick(View v) {
final Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR); // current year
int mMonth = c.get(Calendar.MONTH); // current month
int mDay = c.get(Calendar.DAY_OF_MONTH); // current day
datePickerDialog = new DatePickerDialog(activity, new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
t1.setText(dayOfMonth + "/" + (monthOfYear + 1) + "/" + year);
}
}, mYear, mMonth, mDay);
datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis());
datePickerDialog.show();
}
This is the image
What you are facing is the manner how the date picker is implemented. Usually, the title date should go away if you use it like this:
datePickerDialog.setTitle("");
this call have to be directly before datePickerDialog.show();
You need to give a "time" for the fragment to be rendered.
Try this:
datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis() - 1000);
datePickerDialog.getDatePicker().setMaxDate(System.currentTimeMillis() + 1000);

How to convert datepicker format to dd-MM-yyyy

In my database table I use a date format which inserts dates like 04-04-2015.
Then using a datePicker through variable from_date I choose the same date and that date is like 4-4-2015. If I want to select rows using the date selected
from datepicker I get no rows even though rows are available. How can I change the
datePicker date to 04-04-2015 from 4-4-2015, or insert the date like
4-4-2015 instead of 04-04-2015?
private DatePickerDialog.OnDateSetListener myDateListener = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker arg0, int year, int month, int day) {
dateView.setText(new StringBuilder()
// Month is 0 based so add 1
.append(day).append("-") //day
.append(month+1).append("-")//month
.append(year).append(" "));//year
from_date=dateView.getText().toString();
startActivity(new Intent(datefrom.this, dateto.class));
}
};
Code for insertion:
contentvalues.put(VivzHelper.TX_DATE, new SimpleDateFormat("dd-MM-yyyy").format(new Date()));
Using String.format you can achieve what you need.
int day=5,month=4,year=2015;
String date=String.format("%02d-%02d-%d ", day,month,year);
//output date =05-04-2015
private String getDateTime(int year, int month, int day){
Calendar cal = Calendar.getInstance();
cal.set(year, month, day);
String format = "dd-MM-yyyy";
return new SimpleDateFormat(format).format(cal.getTime());
}
You can achieve this using SimpleDateFormat class. For more information visit http://developer.android.com/reference/java/text/SimpleDateFormat.html.
private DatePickerDialog.OnDateSetListener myDateListener = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker arg0, int year, int month, int day) {
Calendar myCalendar = Calendar.getInstance();
myCalendar.set(year, month, day);
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault());
String dateString = formatter.format(myCalendar.getTime());
dateView.setText(dateString);
from_date=dateString;
startActivity(new Intent(datefrom.this, dateto.class));
}
};

DateFormat produces incorrect output

I've got a couple of Buttons that initially display the current date and the current time, respectively. When clicking in the Button that displays the date, it shows a DatePickerFragment that allows the user to choose a date, and then changes the Button's text to the date selected by the user. The other Button does exactly the same but with a TimePickerFragment.
To initialize the Buttons I use the following code:
protected void onCreate(Bundle savedInstanceState){
...
df = DateFormat.getDateInstance();
tf = DateFormat.getTimeInstance();
initDate = new GregorianCalendar();
...
updateDateButtons();
updateTimeButtons();
}
private void updateTimeButtons() {
tf.setCalendar(initDate);
String text = tf.format(initDate.getTime());
btnIniTime.setText(text.substring(0, text.lastIndexOf(":")));
}
private void updateDateButtons() {
df.setCalendar(initDate);
btnIniDate.setText(df.format(initDate.getTime()));
}
Initially, both buttons behave in an expected manner: btnIniTime shows the current time, and btnIniDate shows the current date.
As I said, when the user clicks the btnIniTime button, it shows a TimePickerFragment that prompts the user to choose a time, and the selected time is correctly displayed in btnIniTime.
The problem starts with btnIniDate, that should do the same, but using a DatePickerFragment instead of a TimePickerFragment. When the user selects a date, the button then displays an incorrect date. For example, if I choose 2013 Aug 30, the displayed date turns to be 2013 Aug. 26. If I choose 2013 Sep 1, it then shows 2013 Sep 29!
The classes and methods that I use to change the date ara arranged in the following way:
public abstract static class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
protected TaskActivity activity;
protected Calendar c;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
this.activity = (TaskActivity) activity;
}
#Override
public abstract Dialog onCreateDialog(Bundle savedInstanceState);
public void onDateSet(DatePicker view, int year, int month, int day) {
if(activity instanceof TaskActivity){
setDateResult(year, month, day);
}
}
protected abstract void setDateResult(int year, int month, int day);
}
public static class InitDatePickerFragment extends DatePickerFragment {
#Override
protected void setDateResult(int year, int month, int day) {
activity.setInitDate(year, month, day);
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar c = activity.getInitDate();
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 Calendar getInitDate() {
return initDate;
}
public void setInitDate(int year, int month, int day){
Log.d("TaskActivity", "Year: " + year + "; Month: " + month + "; Day: " + day);
initDate.set(Calendar.YEAR, year);
initDate.set(Calendar.MONTH, month);
initDate.set(Calendar.DAY_OF_WEEK, day);
updateDateButtons();
}
When you push the button:
#Override
public void onClick(View v) {
if(v.equals(btnIniDate)){
DialogFragment newFragment = new InitDatePickerFragment();
newFragment.show(getSupportFragmentManager(), "initDatePicker");
}
...
}
By the way, when setting the date, LogCat produces the following output (I've chosen 2013 Aug 30):
Year: 2013; Month: 7; Day:30
The Problem might be
initDate.set(Calendar.DAY_OF_WEEK, day);
in your setInitDate(). This updates only the day of the week. So your date jumps +-6
use
initDate.set(Calendar.DAY_OF_MONTH, day);

Categories

Resources