I am new to Android.I have a requirement, I have a field to enter the Date Of Birth of a person.On successful selection I wanna return the total number of months from the DOB to current date.For example, if I entered DOB as 19/10/2012 I wanna return 36(months).I searched for this, but didn't find anything suitable to my requirement.Here is my current code which return sucessful data,
private void showDate(int year, int month, int day) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(0);
cal.set(year, month, day);
Date date = cal.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
if(System.currentTimeMillis() > date.getTime()) {
edtDate.setText(sdf.format(date));
LocalDate date1 = new LocalDate(date);
LocalDate date2 = new LocalDate(new java.util.Date());
PeriodType monthDay = PeriodType.yearMonthDayTime();
Period difference = new Period(date1, date2, monthDay);
int months = difference.getMonths();
months=months + 1;
System.out.println("16102015:Nunber of Months"+months);
}else{
Toast.makeText(mActivity,getResources().getString(R.string.date_validationmsg),Toast.LENGTH_LONG).show();
}
}
Calendar startCalendar = new GregorianCalendar();
startCalendar.setTime(startDate);
Calendar endCalendar = new GregorianCalendar();
endCalendar.setTime(endDate);
int diffYear = endCalendar.get(Calendar.YEAR) - startCalendar.get(Calendar.YEAR);
int diffMonth = diffYear * 12 + endCalendar.get(Calendar.MONTH) - startCalendar.get(Calendar.MONTH);
To start with, I'd suggest using LocalDate instead of DateTime for the computations. Ideally, don't use java.util.Date at all, and take your input as LocalDate to start with (e.g. by parsing text straight to that, or wherever your data comes from.) Set the day of month to 1 in both dates, and then take the difference in months:
private static int monthsBetweenDates(LocalDate start, LocalDate end) {
start = start.withDayOfMonth(1);
end = end.withDayOfMonth(1);
return Months.monthsBetween(start, end).getMonths();
}
UPDATE 1
see this link the OP is accepted the same answer because Months.monthsBetween() method is not working proper for him
UPDATE 2
LocalDate userEnteredDate = LocalDate.parse( new SimpleDateFormat("yyyy-MM-dd").format(date));
LocaleDate currentDate = LocalDate.parse( new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
int months = monthsBetweenDates(userEnteredDate, currentDate)
Using Joda-time library here, I was able to get the desired result.
Try the below code it would give the desired the difference in months.
DateTime date1 = new DateTime().withDate(2012, 10, 19);
DateTime today = new DateTime().withDate(2015, 10, 19);
// calculate month difference
int diffMonths = Months.monthsBetween(date1.withDayOfMonth(1), today.withDayOfMonth(1)).getMonths();
Using JodaTime, it's really easy:
http://www.joda.org/joda-time/apidocs/
int nMonths = new Period(startTime, endTime).getMonths();
Use this code to calculate months between two dates
public static int monthsBetweenUsingJoda(Date d1, Date d2) {
return Months.monthsBetween(new LocalDate(d1.getTime()), new LocalDate(d2.getTime())).getMonths();
}
Related
In my application i am displaying a calendar of days in a horizontal scrollable listview like below :
The dates are proper and the current date is also selected, the issue i am facing is the week day that is displayed.It is not proper. The code written to displayed this kind of calendar is as follows:
int count = 0;
for (int i = 1; i <= noOfDays; i++) {
int year = Calendar.YEAR;
int month = Calendar.MONTH;
int day = i;
Calendar c = new GregorianCalendar(year, month, day);
c.set(year, month, day);
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
String d = sdf.format(cal1.getTime());
CustomData custom = new CustomData(String.valueOf(i),
getWeekday(c.get(Calendar.DAY_OF_WEEK)), d);
mCustomData[count] = custom;
Log.e("mCustomData", d);
count++;
if(Integer.parseInt(splitDateee[0])==i)
{
currentDate = i-1;
}
}
There is an error in weekdays that is being displayed. What am i missing here? Not able to figure out the issue.
Please help ! Thanks in Advance!
int year = Calendar.YEAR;
int month = Calendar.MONTH;
These are flags belonging to calendar to get and set values, and do not indicate the current year and month. You would need to get the year and month from the current device time and do:
int year = currentYear;
int month = currentMonth;
Calling Calendar.getInstance() gets the calendar for the current day:
Calendar now = Calendar.getInstance();
You can then use the flags like so:
int month = now.get(Calendar.MONTH);
int year = now.get(Calendar.YEAR);
I have implemented datepicker dialog in my app successfully, have doubt in disabling the dates, check it out my code
To get the year which is 13 year above the current year
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
String now = df.format(new java.util.Date());
String[] datevalues = now.split("/");
int yearsum = Integer.parseInt(datevalues[2]);
int i;
for (i = 0; i < 13; i++) {
yearsum = yearsum - 1;
Log.d("i", "i" + i + yearsum);
}
finaldate = yearsum;
My DatePicker dialog
Calendar calender = Calendar.getInstance();
int year = calender.get(Calendar.YEAR);
int month = calender.get(Calendar.MONTH);
int day = calender.get(Calendar.DAY_OF_MONTH);
Date newDate = new Date(Long.parseLong(getString(finaldate)));
DatePickerDialog dialog = new DatePickerDialog(Signup.this,
new DateListener(), year, month, day);
// To set the maximum year
dialog.getDatePicker().setMaxDate(finaldate);
dialog.show();
Now i need to show the date upto the date which is 13 years before the current date,
i have used dialog.getDatePicker().setMaxDate(finaldate);
line to filter the dates but no luck.`have tried with google but dint get the proper solution. help me to get the solution.
Thanks
To calculate a date 13 years ago from today:
Calendar then = Calendar.getInstance();
then.add(Calendar.YEAR, -13);
To apply it as the max date in date picker:
...getDatePicker().setMaxDate(then.getTimeInMillis());
I am using DatePickerDialog to show the calender. I want to access First day and last day of the week of the date selected.
Here is what I have tried
this.tv_date.setText( new StringBuilder()
// Month is 0 based so add 1
.append(mDay).append("-")
.append(monthName).append("-")
.append(mYear).append(""));
tv_date.setHighlightColor(Color.CYAN);
String str=mDay+"-"+mMonth+"-"+mYear;
SimpleDateFormat sdf=new SimpleDateFormat("dd-MM-yyyy");
sdf.format(""+str); //here I am getting exception
Calendar cal=Calendar.getInstance();
int s= cal.getFirstDayOfWeek();
Toast.makeText(getApplicationContext(), "first day of the week : "+s, 1).show();
But I am getting "IllegalArguementException".
Please help me
Thanks
sdf.format(""+str); - is wrong. You either need to pass a Date object to it, or else, change it to sdf.parse(str); to get a Date object from it.
Edit:- To get the first day of the week, do this.
String str=mDay+"-"+mMonth+"-"+mYear;
SimpleDateFormat sdf=new SimpleDateFormat("dd-MM-yyyy");
Date myDate = new Date();
try{
myDate = sdf.parse(str);
}catch(ParseException pe){
// Do Something
}
Calendar cal = Calendar.getInstance();
cal.setTime(myDate);
cal.set(Calendar.DAY_OF_WEEK, 1);
int s = cal.get(Calendar.DATE);
Here is an example of calculating the first day of week.
private void firstDayOfThisWeek(){
DateTime today = DateTime.today(TimeZone.getDefault());
DateTime firstDayThisWeek = today; //start value
int todaysWeekday = today.getWeekDay();
int SUNDAY = 1;
if(todaysWeekday > SUNDAY){
int numDaysFromSunday = todaysWeekday - SUNDAY;
firstDayThisWeek = today.minusDays(numDaysFromSunday);
}
System.out.println("The first day of this week is : " + firstDayThisWeek);
}
Instead of assigning today you can assign any other day with exact format
I am getting date and time from DatePicker and TimePicker like:
int dateofmonth = date.getDayOfMonth();
int month = date.getMonth() + 1;
int year = date.getYear();
int hour = time.getCurrentHour();
int minutes = time.getCurrentMinute();
But i want date and time like this format:
Friday, December 14,2012 - 4:30 PM.
Any help?
formate it as you want ....
public void SetMyCustomFormat()
{
// Set the Format type and the CustomFormat string.
dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.CustomFormat = "put your formate here ";
}
for more help
http://msdn.microsoft.com/en-us/library/system.windows.forms.datetimepicker.customformat.aspx
You could try to use SimpleDateFormat, see SimpleDateFormat
Under the examples section is a date that represents your required format.
You need to create a Date Object first from Calendar, you can do as below:
Calendar cal= Calendar.getInstance();
cal.setTime(new Date());
int dateofmonth = date.getDayOfMonth();
int month = date.getMonth();
int year = date.getYear();
cal.set(dateofmonth, month, year);
Now create a SimpleDateFormat object, with the format, you desire, and format date with that format, by
String formattedDate=simpleDateFormat.format(cal.getTime());
If all you need is formatting a Date object in the current locale, you can use DateFormat:
Calendar date = Calendar.getInstance();
date.set(Calendar.YEAR, picker.getYear());
...
String str = DateFormat.getDateTimeInstance().format(date);
The method getDateTimeInstance() returns the preferred display for the current locale, which is desirable to internationalize your application because different locales have different preferences for the order of the components. For example:
US: Friday, December 14,2012 - 4:30 PM
Italy: Venerdì 14 Dicembre 2012, 16:30
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;