I want to parse a date from a string and set it in the DatePickerDialog:
try {
myCalendar.setTime(mySimpleFormatter.parse(jsonObj.getString("dob")));
} catch (ParseException e) {
System.out.println("!!!");
}
myEditBox.setText(mySimpleFormatter.format(myCalendar.getTime()));
myDatePickerDialog.getDatePicker().updateDate(myCalendar.getTime().getYear()); // depricated
But the issue is that myCalendar.getTime().getYear(), getMonth(), getDay are deprecated. What should be used then?
Calendar cal = Calendar.getInstance();
cal.setTime(myDate);
int day= cal.get(Calendar.DAY_OF_MONTH);
the Date.getYear(), getMonth() and getDay() are deprecated and specifically ask you to use Calendar.get()
Here is the relevant note from the API documentation
Deprecated. As of JDK version 1.1, replaced by Calendar.get(Calendar.YEAR) - 1900.
http://download.oracle.com/javase/6/docs/api/java/util/Date.html#getYear%28%29
I have used this code :
private void setDateTimeField(){
usereditbirthdateedittext.setOnClickListener(this);
Calendar newCalendar = Calendar.getInstance();
fromDatePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar newDate = Calendar.getInstance();
newDate.set(year, monthOfYear, dayOfMonth);
SimpleDateFormat dateFormatter = new SimpleDateFormat("dd/MM/yyyy");
usereditbirthdateedittext.setText(dateFormatter.format(newDate.getTime()));
selectedDate = new Date(newDate.getTimeInMillis());
}
},newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
}
Kotlin solution :
Calendar.getInstance().get(Calendar.MONTH + 1)
The value returned from get(Calendar.MONTH) is between 0 and 11, with the value 0 representing January, so you need to add +1 to get the current month.
You're actually calling methods on Date, which are deprecated. (myCalendar.getDate() returns a Date object).
On an instance of Calendar, you can use get() and pass it constants to get year, month, date, and more (refer to the linked docs for get()).
I will recommend you to use JodaTime instead as it is more powerful and can solve all of the Date related issues.
Here is the example sample:
DateTimeFormatter fromFormat = DateTimeFormat.forPattern("dd/MM/yyyy"); // String pattern of your DOB from which you want to create DateTime Object
DateTime dob = fromFormat.parseDateTime(jsonObj.getString("dob")); // This will give you DateTime Object
DateTimeFormatter toFormat = DateTimeFormat.forPattern("MMMM dd, yyyy"); // String pattern of your parsed DOB
myEditBox.setText(dob.toString(toFormat)); // April 2, 2016
myDatePickerDialog.getDatePicker().updateDate(dob.getYear());
Related
I have a DatePickerDialog in my app and I want the date selected by the user to be restricted until the current date. I am comparing the date selected from the DatePickerDialog with the newDate() and if the selected date is before, I am throwing an error. Please find the code as follows.
DatePickerDialog datePickerDialog = new DatePickerDialog(this,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
Calendar calendar = Calendar.getInstance();
calendar.set(year, monthOfYear, dayOfMonth);
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
String visitDate = dateFormat.format(calendar.getTime());
try {
Date appointDate = dateFormat.parse(visitDate);
Date currentDate = new Date();
if(appointDate.before(currentDate)){
appointmentDateInputLayout.setError("Date selected is not within range!");
}else{
appointmentDateEditText.setText(visitDate);
appointmentDateInputLayout.setError(null);
}
} catch (ParseException e) {
e.printStackTrace();
}
appointmentDateEditText.setText(visitDate);
}
}, mYear, mMonth, mDay);
datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis());
datePickerDialog.show();
But when I do this, I am getting an error for selecting today's date also. I want the user to allow the current date. What am I missing here?
Kindly help.
Look, the
Date currentDate = new Date() ;
allocates the date object at the time it was instantiated in the degree of Milliseconds so alternating the allocation and putting date object at the first of the code would give the very early time so the time that you take to choose visitdate would be eventually greater (after) so the number of Milliseconds in the currentDate will be less than number of Milliseconds in the Picked new Date
Try to compare with calendar getTime() method instead of current date.:
If(appointDate.before(calendar.getTime())
I am using SimpleDateFormat to convert the date from dd-MM-yyyy to yyyy-MM-dd
but I does not display the year properly.I am trying to convert 18-5-2014 to 2014-05-18
but I am getting 3914-05-18.
public void onDateSet(DatePicker view, int year,int monthOfYear, int dayOfMonth)
{
Date selectedDate = new Date(year,monthOfYear, dayOfMonth);
String strDate = null;
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
strDate = dateFormatter.format(selectedDate);
txtdeliverydate.setText(strDate);
}
I suspect you didn't read the documentation for the (deprecated) Date constructor you're using:
Parameters:
year - the year minus 1900.
month - the month between 0-11.
date - the day of the month between 1-31.
Avoid using Date here. Either use a good date/time library like Joda Time, or use Calendar to set year/month/day values - even then, the month will be 0-based.
Also, your method is currently accepting year/month/day values... if you're actually just trying to do a conversion, you should be accepting a string and returning a string, e.g.
public static String convertDateFormat(String text) {
TimeZone utc = TimeZone.getTimeZone("Etc/UTC");
SimpleDateFormat parser = new SimpleDateFormat("dd-MM-yyyy", Locale.US);
parser.setTimeZone(utc);
Date date = parser.parse(text);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
formatter.setTimeZone(utc);
return formatter.format(date);
}
I have 3 strings containing day, month and year values. For example:
String mday = "02";
String mmonth="07";
String myear="2013";
I need to set the DatePicker in my activity to a month from the date above. I do not mean just add 1 to the mmonth value... in case of day 31 I would end up with an invalid date.
So I need some way to increment the date (the valid way) and set the DatePicker with it's value.
I am aware that setting the datePicker with Int values is done like this:
DatePicker datepicker = (DatePicker) findViewById(R.id.datePicker1);
datepicker.init(iYear, iMonth, iDay, null);
// where iYear,iMonth and iDay are integers
But how do I obtain the integer values of day,month and year of an incremented DATE by one month?
So between the first values (strings) and final values of incremented date(integers) what are the steps that I must make?
I assume I would have to use a Calendar.
So my code should look like this:
Integer iYear, iMonth, iDay = 0;
String mday = "02";
String mmonth="07";
String myear="2013";
Calendar cal = Calendar.getInstance();
cal.set(Integer.parseInt(myear), Integer.parseInt(mmonth), Integer.parseInt(mday));
cal.add(Calendar.MONTH, 1);
// here I should get the values from cal inside the iYear, iMonth, iDay, but I do not seem to succeed.
DatePicker datepicker = (DatePicker) findViewById(R.id.datePicker1);
datepicker.init(iYear, iMonth, iDay, null);
if I do:
datepicker.init(cal.YEAR, cal.MONTH, cal.DATE, null);
then application crashes.
What should I do?
How to set this incremented by a month date into my DatePicker?
UPDATE
I changed my test code to this:
Calendar cal = Calendar.getInstance();
cal.set(2013, 05, 23);
cal.add(Calendar.MONTH, 1);
int xxday = cal.get(Calendar.DATE);
int xxmonth = cal.get(Calendar.MONTH);
int xxyear = cal.get(Calendar.YEAR);
datepicker.init(xxyear, xxmonth, xxday, null);
but Now the datePicker is set to one month from NOW instead of one month from the wanted date So instead of (2013-06-23) I have (2013-09-23). I assume it's because of
int xxmonth = cal.get(Calendar.MONTH);
how can I get the real month from a Calendar cal; ?
DatePicker class has a method updateDate(year, month, dayOfMonth) which you can use to set a date in your DatePicker as shown below:
DatePicker datePicker = (DatePicker) findViewById(R.id.datePicker1);
datePicker.updateDate(2016, 5, 22);
Calendar month is 0 based. So month 07 is August.
Use the following code to initialize the calendar object if you have a date picker:
Calendar calendar = new GregorianCalendar(datePicker.getYear(),
datePicker.getMonth(),
datePicker.getDayOfMonth());
Else hard-code the date parts in the constructor
use this tuto to create your DatePickerDialog then use this code inside DatePickerDialog
https://developer.android.com/guide/topics/ui/dialogs.html
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
String mday = "02";
String mmonth="07";
String myear="2013";
//convert them to int
int mDay=Integer.valueOf(mday);
int mMonth=Integer.valueOf(mmonth);
int mYear=Integer.valueOf(myear);
return new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
String d=convertToCompletDate(i2,i1,i);
mListener.onDatePicked(d);
}
},mYear,mMonth,mDay);
}
In Kotlin
Assuming your date is a string. i.e:
var defaultDate = "20/4/2022"
you could use
val datePicker = findViewById<DatePicker>(R.id.date_Picker)
var defaultDate = eventDate.toString().split(Regex("/"))
var dd = defaultDate[0].toInt()
var mm = defaultDate[1].toInt()
var yy = defaultDate[2].toInt()
datePicker.updateDate(yy,mm,dd)
The past few days I've been searching for ways to get a 'readable' date out of my calendarview from android 4.0. I can't manage to find a solution or example that suits my problem. I did get it in miliseconds but not in a date format.
My problem is: I have a calendarview and I want the selected date by the user, shown in logcat in a dateformat yy-mm-dd.
I was used to the datepicker from android 2.2 and I'm not familiar with calendarview and can't find much about it either. Does anyone know a solution for this?
Okay so here is how to do this. When you fire your calendarview activity or a calendarview inside your activity it sets the date to the current date(meaning today). To get this current date just use the Calendar object provided by the java api to get this date example below:
Calendar date = Calendar.getInstance();
// for your date format use
SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd");
// set a string to format your current date
String curDate = sdf.format(date.getTime());
// print the date in your log cat
Log.d("CUR_DATE", curDate);
to get a date changed you must do this
CalendarView myCalendar = (CalendarView) findViewById(R.id.myCalenderid);
myCalendar.setOnDateChangeListener(myCalendarListener);
OnDateChangeListener myCalendarListener = new OnDateChangeListener(){
public void onSelectedDayChange(CalendarView view, int year, int month, int day){
// add one because month starts at 0
month = month + 1;
// output to log cat **not sure how to format year to two places here**
String newDate = year+"-"+month+"-"+day;
Log.d("NEW_DATE", newDate);
}
}
kandroidj's answer helps to create date, but not date of correct format.
So to format selected date:
calendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
#Override
public void onSelectedDayChange(CalendarView view, int year, int month,
int dayOfMonth) {
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
Calendar calendar = Calendar.getInstance();
calendar.set(year, month, dayOfMonth);
String sDate = sdf.format(calendar.getTime());
Log.d(TAG, "sDate formatted: " + sDate);
}
});
You should use SimpleDateFormat
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
String selectedDate = sdf.format(new Date(calendar.getDate()));
long date = calenderView.getDate();
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(date);
int Year = calendar.get(Calendar.YEAR);
int Month = calendar.get(Calendar.MONTH);
int Day = calendar.get(Calendar.DAY_OF_MONTH);
//customize According to Your requirement
String finalDate=Year+"/"+Month+"/"+Day;
In my application i have 1 edittext box,in this user will enter some date.What i want is i have to get the date of 7th day from the user entered date.I searched in google,i found 1 solution.
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Calendar cal = Calendar.getInstance();
cal.add("field", +7);
String currentDateandTime = sdf.format(cal.getTime());
In the above cal.add("field",+7)-->Field is int.But my date format is string.So i cant use here..Please help me..
Get date from SimpleDateFormat and add this date object to calender then change into calender. And again get new Updated date from Calender. Wait i will post code
try {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date UserEnterDate = sdf.parse("String from your editbox");
Calendar calendar = Calendar.getInstance();
calendar.setTime(UserEnterDate);
int day = calendar.get(Calendar.DAY_OF_MONTH);
day = day + 7;
calendar.set(Calendar.DAY_OF_MONTH, day);
String newDate = calendar.get(Calendar.DAY_OF_MONTH) + "/"
+ calendar.get(Calendar.MONTH) + "/"
+ calendar.get(Calendar.YEAR);
} catch (Exception e) {
// TODO: handle exception
}
As you said thatyou got the date in string format.
So let me start from there
Suppose the date is:
String dt = "2008-01-05"; // Start date
Then do thhis::
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
try {
c.setTime(sdf.parse(dt));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
c.add(Calendar.DATE, 7); // number of days to add
dt = sdf.format(c.getTime());
System.out.println(""+dt);
Hope.this will definitely help you.
Enjoy!!!
I suggest better you use DatePickerDialog in onClick() of EditText
then you will get individual Date Month Year. Then you can set your date
Date+=7
you can get Date Object from a String if you know the format, by your question the format is:
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Calendar cal = Calendar.getInstance();
cal.add("field", +7);
String currentDateandTime = sdf.format(cal.getTime());
now use this date format to parse a string to get Date object, say:
Date dt=sdf.parse(txtDt.getText().toString());
now Set this date to Calendar Object:
Calendar cal=Calendar.getInstance();
cal.setTime(dt);
now you need to add 7 days to this date, so do as:
cal.add(Calendar.DAY_OF_MONTH, 7);
now you have been added 7 days to the date successfully, now get Date from this Calendar object, by using:
Date dtNew=cal.getTime();
and you can convert it to readable string using:
String strNewDt=sdf.format(dtNew);
You have to write the name of the field you want to modify to the "field" parameter, here#s a link to the calendar reference. The calendar object is not a string, but a whole different creature that youre using. Use its functions to do it.
http://developer.android.com/reference/java/util/Calendar.html
And so you would write
!edit, you actually have to set the calendar using ints and parse your string to match. use the set function from the calendar:
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Calendar cal = new Calendar;
cal.set(int year, int month, int day, int hourOfDay, int minute)
cal.add(DATE, 7);
String currentDateandTime = sdf.format(cal.getTime());