This code pick date next is triggered when a button is clicked; and then it adds +3 month to the picked date.
displayDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datepicker = new DatePickerDialog(Remainder.this, android.R.style.Theme_Holo_Light_Dialog_MinWidth, onDateSetListener, year,month,day);
datepicker.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
datepicker.show();
}
});
onDateSetListener = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int day) {
month = month+1;
Log.d(TAG, "onDateSet: mm/dd/yyyy: " + month + "/" + day + "/" + year);
String date = month + "/" + day + "/" + year;
displayDate.setText(date);
}
};
You can use Calendar class initialized with GregorianCalendar instance and then use the Calendar's add() method to add months to your date.
And then use get() method to:
get the day of the month by: calendar.get(Calendar.DAY_OF_MONTH)
get the month (range 0-11) by: calendar.get(Calendar.MONTH)
get the year by: calendar.get(Calendar.YEAR)
To apply this to your code:
onDateSetListener = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int day) {
Calendar calendar = new GregorianCalendar(year, month, day);
calendar.add(Calendar.MONTH, 3); // adding 3 months
int newMonth = calendar.get(Calendar.MONTH) + 1;
Log.d(TAG, "onDateSet: mm/dd/yyyy: " + newMonth + "/" + calendar.get(Calendar.DAY_OF_MONTH) + "/" + calendar.get(Calendar.YEAR));
String date = newMonth + "/" + calendar.get(Calendar.DAY_OF_MONTH) + "/" + calendar.get(Calendar.YEAR);
displayDate.setText(date);
}
};
Related
I am using below code for the date of birth in registration of the user, but when using it is getting the month of the birth one less, example birth month is September it is registering in database birth month as august, and this date of birth is being registered in numerics and format is dd/mm/yyyy
I want the accuracy with the month. please assist
public void showDateDialog() {
Calendar cal = Calendar.getInstance();
final int day = cal.get(Calendar.DAY_OF_MONTH);
int month = cal.get(Calendar.MONTH) ;
int year = cal.get(Calendar.YEAR);
DatePickerDialog.OnDateSetListener listener = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
if (day < 10 && monthOfYear < 10)
date = "0" + dayOfMonth + "/0" + monthOfYear + "/" + year;
else if (day < 10 && monthOfYear > 10)
date = "0" + dayOfMonth + "/" + monthOfYear + "/" + year;
else if (day > 10 && monthOfYear < 10)
date = dayOfMonth + "/0" + monthOfYear + "/" + year;
else
date = dayOfMonth + "/" + monthOfYear + "/" + year;
dateOfBirth.setText(date);
}
};
DatePickerDialog dpDialog = new DatePickerDialog(this, listener, year, month, day);
dpDialog.show();
}
Calendar count month from 0 to 11.
So that you get one month difference.So you add 1 always.
int month = cal.get(Calendar.MONTH) + 1
I am trying to check that my user should be 18 years old. If Not then show a toast. (Trying to get from exact today date). But result is getting success only year wise.
Output - Years are getting calculated.
Expected - From today's date, user should be 18 years old.
this is what i have tried.
val calendar = Calendar.getInstance()
val year = calendar.get(Calendar.YEAR)
val month = calendar.get(Calendar.MONTH)
val day = calendar.get(Calendar.DAY_OF_MONTH)
val dpd = DatePickerDialog(this, DatePickerDialog.OnDateSetListener { view, year, monthOfYear, dayOfMonth ->
calendar.set(Calendar.YEAR, year)
calendar.set(Calendar.MONTH, monthOfYear)
calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth)
val sdf = SimpleDateFormat(myFormat, Locale.US)
val dob = sdf.format(calendar.time)
val userAge = GregorianCalendar(year, month, day)
val minAdultAge = GregorianCalendar()
minAdultAge.add(Calendar.YEAR, -18)
minAdultAge.add(Calendar.MONTH, -1)
if (minAdultAge.before(userAge)) {
Toast.makeText(this, getString(R.string.txt_18_years_age_validation), Toast.LENGTH_SHORT).show()
} else {
etDob!!.setText(dob)
}
}, year, month, day
)
dpd.datePicker.maxDate = Calendar.getInstance().timeInMillis
dpd.show()
What modifications needed to get validations for todays date.
Thank You.
Try turning minAdultAge and the DOB into millis for comparing
minAdultAge.timeInMillis > dob.timeInMillis
I've edited to show how you could validate the exact age based on the day.
It's meant as a help not a solution.
public static void main(String[] args) {
Calendar present = Calendar.getInstance();
Calendar personBirthDate = Calendar.getInstance();
personBirthDate.set(Calendar.YEAR, 2001);
personBirthDate.set(Calendar.DAY_OF_YEAR, personBirthDate.get(Calendar.DAY_OF_YEAR) - 1); // yesterday
int yearDiff = present.get(Calendar.YEAR) - personBirthDate.get(Calendar.YEAR);
int dayDiff = present.get(Calendar.DAY_OF_YEAR) - personBirthDate.get(Calendar.DAY_OF_YEAR);
System.out.println("Day of person birth year " + personBirthDate.get(Calendar.DAY_OF_YEAR));
System.out.println("Day of current year " + present.get(Calendar.DAY_OF_YEAR));
System.out.println("Years between " + yearDiff);
if(present.get(Calendar.DAY_OF_YEAR) - personBirthDate.get(Calendar.DAY_OF_YEAR) > 0){
System.out.println("You are only " + (yearDiff - 1) + " years old");
}else if(present.get(Calendar.DAY_OF_YEAR) - personBirthDate.get(Calendar.DAY_OF_YEAR) < 0) {
System.out.println("You are already " + yearDiff + " years old");
}else{
System.out.println("You are exactly " + yearDiff + " years old");
}
}
This question already has answers here:
How to iterate through range of Dates in Java?
(15 answers)
Closed 5 years ago.
I am having doubt that how can i iterate through the days in java (Android). Requirement is i am displaying whole week dates.
Note: "whichever date user selects from it should start".
ex: If date is 29-10-2017 then the output will be 29-10-2017, 30-10-2017, 31-10-2017, 1-11-2017, 2-11-2017, 3-11-2017, 4-11-2017.
This is whole week.
I was able to get this result when dates are inside that month, but when dates are exceeding the month or year, i am not able to resolve them.
Please help, how do i resolve this issue.
Below is the code-snippet which i am using for this:
Calendar startCal = Calendar.getInstance();
startCal.setTime(new Date(Long.MAX_VALUE));
startCal.setTimeInMillis(minDate.getDateInMillis());
Calendar endCal = Calendar.getInstance();
endCal.setTime(new Date(Long.MAX_VALUE));
endCal.setTimeInMillis(maxDate.getDateInMillis());
// Add all weekend days within range to disabled days
for (int i = 0; i < 7; i++) {
while (startCal.before(endCal) || startCal.equals(endCal) || (startCal.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY)) {
if (startCal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY
|| startCal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY
|| startCal.get(Calendar.DAY_OF_WEEK) == Calendar.TUESDAY
|| startCal.get(Calendar.DAY_OF_WEEK) == Calendar.WEDNESDAY
|| startCal.get(Calendar.DAY_OF_WEEK) == Calendar.THURSDAY
|| startCal.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY) {
int key = Utils.formatDisabledDayForKey(startCal.get(Calendar.YEAR),
startCal.get(Calendar.MONTH), startCal.get(Calendar.DAY_OF_MONTH));
disabledDays.put(key, new MonthAdapter.CalendarDay(startCal));
}
startCal.add(Calendar.DATE, 1);
}
}
int daysInMonth = startCal.getActualMaximum(Calendar.DAY_OF_MONTH); // 31
And to poulet them inside some textview i am using this below code-snippet:
String date = dayOfMonth + "-" + (monthOfYear + 1) + "-" + year;
arr1 = new String[7];
datepicker_dailog.setText(date);
// String input = datepicker_dailog.getText().toString();
Log.e(TAG, "Date value1 is:--- " + date);
GregorianCalendar cal=new GregorianCalendar();
if (cal.isLeapYear(year)) {
dayOfMonth++;
}
String ar[] = date.split("[-]");
int day = Integer.parseInt(ar[0]);
int month = Integer.parseInt(ar[1]);
int year1 = Integer.parseInt(ar[2]);
Log.e(TAG, "new value is "+ day + " " + month + " "+ year1);
for(int j = 0; j < 7 ; j++) {
date_exp(day, month, year1);
date = day + "-"+month+"-"+year1;
arr1[j] = date;
Log.e(TAG, "loop is :--- "+ arr1[j]);
Log.e(TAG, "value in loop is :--- "+ day + " " + month + " "+ year1);
day++;
}
Log.e(TAG, "updated value is "+ day + " " + month + " "+ year1);
I am refering this library to inplement calendar with date:
https://github.com/code-troopers/android-betterpickers
Here i am modifying and storing the date values in textviews, Please check once:
#Override
public void onDateSet(CalendarDatePickerDialogFragment dialog, int year, int monthOfYear, int dayOfMonth) {
String date = dayOfMonth + "-" + (monthOfYear + 1) + "-" + year;
arr1 = new String[7];
datepicker_dailog.setText(date);
// String input = datepicker_dailog.getText().toString();
Log.e(TAG, "Date value1 is:--- " + date);
GregorianCalendar cal=new GregorianCalendar();
if (cal.isLeapYear(year)) {
dayOfMonth++;
}
String ar[] = date.split("[-]");
int day = Integer.parseInt(ar[0]);
int month = Integer.parseInt(ar[1]);
int year1 = Integer.parseInt(ar[2]);
Log.e(TAG, "new value is "+ day + " " + month + " "+ year1);
for(int j = 0; j < 7 ; j++) {
date = day + "-"+month+"-"+year1;
arr1[j] = date;
Log.e(TAG, "loop is :--- "+ arr1[j]);
Log.e(TAG, "value in loop is :--- "+ day + " " + month + " "+ year1);
day++;
}
Log.e(TAG, "updated value is "+ day + " " + month + " "+ year1);
//------------------------------------------------------------------------------------------
listView=(ListView)findViewById(R.id.addtime_container);
dataModels= new ArrayList<>();
try {
for (int i = 0; i < 7; i++) {
dataModels.add(new Model_Addtime(arr1[i]));
adapter = new Adapter_addtime(dataModels, getApplicationContext());
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Model_Addtime dataModel = dataModels.get(position);
Snackbar.make(view, dataModel.getDate_text() + "\n", Snackbar.LENGTH_LONG).setAction("No action", null).show();
}
});
}
} catch (NumberFormatException num){
num.printStackTrace(); num.getCause(); num.getMessage();
}
}
You should use this code
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
cal.add(Calendar.DATE, 2);
cal.add(Calendar.DATE, 3);
DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
System.out.println(df.format(cal.getTime());
It will handle the month change and year change automatically.
In java 8 you can use streams like in this example
List<LocalDate> daysRange = Stream.iterate(startDate, date -> date.plusDays(1)).limit(numOfDays).collect(toList());
Get instance of calendar, set it to today's date. Calendar has a function of adding 1 day to specified date and it takes care of adding month, year etc. Below is the code. Haven't tested the code though.
// Define the format in which you want dates
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
//Get calendar instance
Calendar calendar = Calendar.getInstance();
//Set today's date to calendar instance
calendar.setTime(new Date());
//Initialize a list to get dates
List<String> dates = new ArrayList<>();
//Get today's date in the format we defined above and add it to list
String date = format.format(calendar.getTime());
dates.add(date);
//run a for loop six times to get 1 day added each time
for (int i = 0; i <= 5; i++){
//this will take care of month and year when adding 1 day to current date
calendar.add(Calendar.DAY_OF_MONTH, 1);
dates.add(format.format(calendar.getTime()));
}
//Then to show the dates to your text-
String listString = TextUtils.join(", ", dates);
yourtextview.setText(listString);
You can use the add() method of Calendar class. It can be used to add or subtract specified number of days to a Calendar instance. The following is a running piece of code
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Calendar;
public class DateExample {
public static void main(String[] args) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-YYYY");
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
String date;
for (int i = 0; i <= 7; i++){
date = dateFormat.format(cal.getTime());
System.out.println(date);
cal.add(Calendar.DAY_OF_MONTH, 1);
}
}
}
You can use iterateDay method. Example usage also below.
public class DateClass {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
calendar.set(2017, Calendar.OCTOBER, 29);
new DateClass().iterateDay(calendar.getTime(), 7);
}
public void iterateDay(Date date, int iterateCount){
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
dislayDate(date);
for (int i = 1; i < iterateCount; i++) {
calendar.add(Calendar.DATE, 1);
dislayDate(calendar.getTime());
}
}
public void dislayDate(Date date){
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
System.out.println(dateFormat.format(date));
}
}
Why does it show strike line on getDate(), getMonth() and getYear(). These methods are used to get current date, month and year but I don't know why it shows strike on these methods.
Code:
public class hello {
public static void main(String[] args) {
int days;
int month;
int year;
days = 24;
month = 10;
year = 1994;
System.out.println("Date of Birth: " + days + "/" + month + "/" + year);
Date d = new Date();
int t = d.getDate();
int x = d.getMonth() + 1;
int f = d.getYear() + 1900;
System.out.println("Current Date: " + t + "/" + x + "/" + f);
}
}
IDEs like Eclipse would strike the methods if they are deprecated, meaning they're not recommended for use because there is a better alternative. See the Javadocs of getDate():
Deprecated. As of JDK version 1.1, replaced by Calendar.get(Calendar.DAY_OF_MONTH).
Using Calendar methods:
Calendar calendar = Calendar.getInstance();
int day = calendar.get(Calendar.DAY_OF_MONTH);
int month = calendar.get(Calendar.MONTH) + 1;
int year = calendar.get(Calendar.YEAR);
That's becuase they're deprecated. If you set the #deprecated in the info above a function, it'll strike methods over in most IDE's.
These specific functions are deprecated because the newer Calendar is a better option.
Try this.
int days;
int month;
int year;
days=24;
month=10;
year=1994;
System.out.println("Date of Birth: "+days+ "/" +month+ "/" +year);
LocalDate dd = LocalDate.of(year, month, days);
System.out.println("Current Date: " + dd);
System.out.println("Month: " + dd.getMonth());
System.out.println("Day: " + dd.getDayOfMonth());
System.out.println("Year: " + dd.getYear());
//If you would add year
LocalDate newYear = dd.plusYears(10);
System.out.println("New Date: " + newYear);
This is output:
Date of Birth: 24/10/1994
Current Date: 1994-10-24
Month: OCTOBER
Day: 24
Year: 1994
New Date: 2004-10-24
I am using Calendar function to set my custom date to calendar. I am setting it like below this but it is giving different date.
int day = Integer.parseInt(String.valueOf(dOutput.getDwDay()));
int monthday = Integer.parseInt(String.valueOf(dOutput.getDwMonth()));
int monthyearday = Integer.parseInt(String.valueOf(dOutput.getDwYear()));
System.out.println("day = " + day);
System.out.println("monthday = " + monthday);
System.out.println("monthyearday = " + monthyearday);
System.out.println("After setting Time: " + calendar.getTime());
calendar.set(Calendar.DATE, day);
calendar.set(Calendar.DAY_OF_MONTH, monthday);
calendar.set(Calendar.DAY_OF_YEAR, monthyearday);
int frommonth = calendar.get(Calendar.MONTH);
int year = calendar.get(Calendar.YEAR);
System.out.println("year = " + year);
System.out.println("frommonth = " + frommonth);
OUTPUT
I am giving this
day = 23
monthday = 5
monthyearday = 2014
But it is generating like this:
year = 2019
frommonth = 6
You are setting the wrong fields on your calendar. Set the fields like this:
calendar.set(Calendar.DAY_OF_MONTH, day); // day
calendar.set(Calendar.MONTH, monthday); // month
calendar.set(Calendar.YEAR, monthyearday); // year