I am wanting to create a gestation period calculator for my app. I want to grab the date that the user had picked in the date time picker and advance that date by 9 months and 10 days and print it out in a textView. I am able to get the date from the date picker and print the date into the textView but what I need to do now is to advance the date by the 9 months and 10 days. Any ideas? and here is my current code for getting the date from the date picker and printing it to a text view.
public class GestationPeriod extends Activity {
DatePicker date;
TextView gestationperiodView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gestationperiod);
setupVariables();
}
public void calculate(View v){
int gestationPeriodMonth = 9;
int gestationPeriodDay = 10;
int year = date.getYear();
int month = date.getMonth();
int day = date.getDayOfMonth();
gestationperiodView.setText("" + day + " / " + month + " / " + year);
}
private void setupVariables(){
date = (DatePicker) findViewById(R.id.datePicker1);
gestationperiodView = (TextView) findViewById(R.id.editText1);
}
Your help would be much appreciated.
Use java.util.Calendar.add(int field, int amount). After getting the day, month, and year, and before gestationperiodView.setText, insert:
Calendar c = new Calendar();
c.set(year, month-1, day);
c.add(Calendar.DAY_OF_MONTH, gestationPeriodDay);
c.add(Calendar.MONTH, gestationPeriodMonth);
day = c.get(Calendar.DAY_OF_MONTH);
month = c.get(Calendar.MONTH) + 1;
year = c.get(Calendar.YEAR);
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);
On one of my app I'm using datepicker class to retrieve data form archive.
I need to set **Max and Min **. On DatePicker.Dialog,
i was able to set **Max to the current time ** however, i counted do for **Min **. if someone to help me i really appreciate it. thanks in advance!
I am looking set setMaxDate = to current year
and setMinDate = two years back from current year(current year -2)
NB: I triad to look if this question was already answered. But, i couldn't get one. all that i see is minData = current timedialog.getDatePicker().setMinDate(new Date().getTime()); which I am not looking for that. i want to set it to different year than the current.
here below part of my code:
// On Clike for Floting button with + signe
#Override
public void onClick(View v) {
switch (v.getId()) {
case imageButtonCalendar:
Calendar c = Calendar.getInstance();
final int[] mYear = {c.get(Calendar.YEAR)};
final int[] mMonth = {c.get(Calendar.MONTH)};
final int[] mDay = {c.get(Calendar.DAY_OF_MONTH)};
DatePickerDialog.OnDateSetListener pDateSetListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
mYear[0] = year;
mMonth[0] = monthOfYear;
mDay[0] = dayOfMonth;
et.setText(new StringBuilder()
// to set date in editext
.append(mDay[0]).append("/").append(mMonth[0] + 1)
.append("/").append(mYear[0]).append(" "));
}
};
DatePickerDialog dialog = new DatePickerDialog(getActivity(), pDateSetListener, mYear[0], mMonth[0], mDay[0]);
dialog.getDatePicker().setMaxDate(new Date().getTime());
dialog.getDatePicker().setMinDate(new Date().getTime(),-year);
dialog.show();
break;
You can use Calendar class :
Calendar cal = Calendar.getInstance()
cal.add(Calendar.DATE, -7);
System.out.println("Date = "+ cal.getTime());
Joda-time is the best Java library for Date.
Get the date after subtracting 2 years :
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.YEAR, -2);
dialog.getDatePicker().setMinDate(calendar.getTime()); // set min date
When i press the button to display the DatePickerDialog, the dialog displays one month greater. For instance, if i initiate with the current date like this(with the DateTime of joda library):
DateTimeZone zone = DateTimeZone.forID("Europe/Athens");
DateTime dt = new DateTime(zone);
int year = dt.getYear();
int month = dt.getMonthOfYear();
int day = dt.getDayOfMonth();
which is 07/08/2014, the date dialog displays one month greater 07/09/2014.
I do not understand why this happens.
The fragment which represents the datePickerFragment is:
#SuppressLint("ValidFragment")
public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener{
#SuppressLint("ValidFragment")
TextView txtDate;
GlobalData appState;
public DatePickerFragment(TextView txtDate) {
super();
this.txtDate = txtDate;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
DateTimeZone zone = DateTimeZone.forID("Europe/Athens");
DateTime dt = new DateTime(zone);
int year = dt.getYear();
int month = dt.getMonthOfYear();
int day = dt.getDayOfMonth();
Log.i("DatePickerFragment day month year", day +" "+ month + " "+ year + "");
// 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) {
appState.setDateUserFrom(year, month, day);
Log.i("Date day month yerar", "Date changed." + day+" " + month + " " +year);
txtDate.setText(new StringBuilder().append(day)
.append("-").append(month).append("-").append(year)
.append(" "));
}
}
DatePickerDialog takes monthOfYear that is 0 to 11 [0 for Jan... 11 for Dec], and your DateTime returns 1 to 12. So you need to do -1 with month value.
Use this:
return new DatePickerDialog(getActivity(), this, year, month - 1, day);
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
DateTimeZone zone = DateTimeZone.forID("Europe/Athens");
DateTime dt = new DateTime(zone);
int year = dt.getYear();
int month = dt.getMonthOfYear()-1;
int day = dt.getDayOfMonth();
Log.i("DatePickerFragment day month year", day +" "+ month + " "+ year + "");
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
Month in date picker starts with zero. So you should subtract one from the getMonthOfYear() to set it on datepicker.
I am pretty sure the reason behind this is because the Android DatePickerDialog expects 0 based month values. Jodatime return them as you would expect it (more human friendly). So just subtract 1 from the month.
Just to clarify, most date functions/libraries are designed with 0 based month values by default. The exception is where explicitly noted, or third party libraries like Jodatime, which make working with date stuff a joy.
Just a guess. Joda month starts at 1 for january but java date at 0? So if you use the current date init with joda the date picker will show the wrong month. Easy solution:
month = dt.getMonthOfYear() - 1;
Try this hope it's worked:
DateTimeZone zone = DateTimeZone.forID("Europe/Athens");
DateTime dt = new DateTime(zone);
int year = dt.getYear();
int month = dt.getMonth();
int day = dt.getDayOfMonth();
OR
DateTimeZone zone = DateTimeZone.forID("Europe/Athens");
DateTime dt = new DateTime(zone);
int year = dt.getYear();
int month = dt.getMonthOfYear() - 1;
int day = dt.getDayOfMonth();
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'd like to get day, month and year values for save to db. These are my codes:
Declaretions:
private TextView tv_purchase_date;
private Button mPickDate;
private int mYear;
private int mMonth;
private int mDay;
OnClickListener listener_show_dlg = null;
OnDateSetListener listener_mdate_display = null;
Event Code:
listener_show_dlg = new OnClickListener() {
public void onClick(View v) {
Calendar cal=Calendar.getInstance();
DatePickerDialog datePickDlg = new DatePickerDialog(
ItemsAddActivity.this,
listener_mdate_display,
cal.get(Calendar.YEAR),
cal.get(Calendar.MONTH),
cal.get(Calendar.DAY_OF_MONTH)
);
datePickDlg.show();
};
};
listener_mdate_display = new OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
mMonth = month;
mYear = year;
mDay = dayofMonth;
tv_purchase_date.setText(dayOfMonth + "/" + monthOfYear + "/" + year);
}
};
}
I try to store mMonth, mYear and mDay values in db. What is the best store type? as integer or as string??
I store in the DB one number that represents the date. It is the number of seconds that have passed since the beginning of the modern era (Jan 1, 1970.) From the Date Picker, you can get the M D Y values like this:
datePickerListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int yearOfYear,
int monthOfYear, int dayOfMonth) {
// the user has picked these values
year = yearOfYear;
month = monthOfYear;
day = dayOfMonth;
Then, I turn these into a single Date object like this.
Calendar cal = new GregorianCalendar(year, month, day);
Date dateOfGames = cal.getTime();
DateFormat df = DateFormat.getDateInstance(DateFormat.LONG);
String cs = df.format(dateOfGames);
changeDateButton.setText(cs); // update the interface
}
};
before I put it in the DB, I turn it into a numebr of seconds like this:
long seconds = date.getTime() / 1000; // this is the date in seconds since the start of the epoch
....
when I take that single number of seconds out of the DB, and want it to be a Date object again, I do this:
date = new Date(seconds * 1000); // converting seconds to a Date object
You can use a DateFormat object to display the date object how you like to see it.
I know this is awkward. Since SQLite doesn't allow you to store a Date, the answer is going to be awkward. Perhaps there is a cleaner way than this, and others will recommned something. :)
I struggled with this issue for a while. I don't konw of anything better than this.
I stored the date in the DB as a single long int. It is pretty easy to convert your Date to the number of seconds since the epoch (Jan 1, 1970), and it is also easy to convert the number of seconds into a Date object.
You need to be careful with seconds and milliseconds.
date = new Date(seconds * 1000); // converting seconds to a Date
seconds = date.getTime() / 1000; // this is the date in seconds since the start of the epoch
// Use Greg calendar to get a Date object from day, month, year
Date dateOfGames = new GregorianCalendar(year, month, day).getTime();
Does that help at all?
I created sqllite table with this sql string:
create table items (id INTEGER PRIMARY KEY AUTOINCREMENT, pdate DATE)
I writed some methods to convert date:
public String date_to_str(Date date) {
String pattern = "dd.MM.yyyy";
SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
Log.d(_watcher_name, "date_to_str" + dateFormat.format(date));
return dateFormat.format(date);
}
public Date mdy_to_date (int day, int month, int year) {
Calendar cal = new GregorianCalendar(year, month, day);
return cal.getTime();
}