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));
}
}
Related
Im trying to compare the real world date with a user input date within a while loop. Although the initial execute is correct, the second time its executing the date stays the same. Ive tried asking for the date inside the while loop and now most recently from within a class method but still the date stays the same.
How can I retrieve an up to date date?
import java.util.Date;
import java.util.Scanner;
class Watch {
Date CurrentTimeAndDate = new Date();
int CurrentMinutes() {
int currentMinutes = CurrentTimeAndDate.getMinutes();
System.out.println(currentMinutes);
return currentMinutes;
}
}
public class App {
public static void main(String[] args) throws InterruptedException {
Scanner input = new Scanner(System.in);
String timer = null;
int i = 0;
int num = 0;
Date TimeAndDate = new Date();
int getDay = TimeAndDate.getDay();
int getMonth = TimeAndDate.getMonth() + 1;
int getYear = TimeAndDate.getYear() + 1900;
int getMinutes = TimeAndDate.getMinutes();
Watch watch1 = new Watch();
String[] Month = { "", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
String[] Day = { "", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" };
System.out.println("Current time and date is " + TimeAndDate);
System.out.println("Printing my way! " + Day[getDay] + " " + Month[getMonth] + " " + getYear + " " + getMinutes);
System.out.println(" Enter a short description of what you want reminding about ");
String rem = input.nextLine();
System.out.println(" Enter date of reminder 1-7");
while (i < 7) {
System.out.println(i + 1 + " = " + Day[i + 1]);
i++;
}
int day = input.nextInt();
System.out.println("Enter Month of reminder");
i = 0;
while (i < 12) {
System.out.println(i + 1 + " " + "=" + " " + Month[i + 1]);
i++;
}
int month = input.nextInt();
System.out.println("Enter year");
int year = input.nextInt();
System.out.println("Enter Minutes, for testing purposes");
int userInputMinutes = input.nextInt();
System.out.println("Date set to remind you about " + rem + " " + Day[day] + " " + Month[month] + " " + year);
if (year > getYear) {
System.out.println("Its time to remind you about ");
} else {
System.out.println("Waiting");
}
int Mins = 0;
while (userInputMinutes != Mins) {
Mins = watch1.CurrentMinutes();
System.out.println("Current Minutes = " + getMinutes);
System.out.println("Entered minutes =" + userInputMinutes);
Thread.sleep(10000);
}
System.out.println("Its time to remind you about " + rem);
}
public static void Date(String time) {
}
}
You are setting the new Date() only once. So you will be getting that same in while loop iterations. To get a new date for every iteration, you have to set the below code inside the while loop
TimeAndDate = new Date();
int getDay = TimeAndDate.getDay();
int getMonth = TimeAndDate.getMonth() + 1;
int getYear = TimeAndDate.getYear() + 1900;
int getMinutes = TimeAndDate.getMinutes();
Watch watch1 = new Watch();
* Note: Date is a deprecated class. Please refer #Ole V.V. answer for
the correct class to use.*
First, use java.time, the modern Java date and time API, for you date and time work. Always. The Date class that you used (misused, really, I’ll get back to that) is poorly designed and long outdated. Never use that.
Getting current minutes
To get the current minute of the hour:
int currentMinutes() {
return LocalTime.now(ZoneId.systemDefault()).getMinute();
}
To read day of week or month from the user
Also use java.time for days of the week and for months. Your code is reinventing wheels. You should prefer to use library classes and methods that are already there for you. For example:
System.out.println(" Enter day of week of reminder 1-7");
for (DayOfWeek dow : DayOfWeek.values()) {
System.out.println("" + dow.getValue() + " = " + dow
.getDisplayName(TextStyle.SHORT_STANDALONE, Locale.ENGLISH));
}
int day = input.nextInt();
DayOfWeek dow = DayOfWeek.of(day);
System.out.println("You have chosen " + dow);
Example interaction:
Enter day of week of reminder 1-7
1 = Mon
2 = Tue
3 = Wed
4 = Thu
5 = Fri
6 = Sat
7 = Sun
2
You have chosen TUESDAY
Most methods of the Date class are deprecated for a reason
As I said, Date is poorly designed and long outdated. More than that, most of the constructors and methods of the class were deprecated in Java 1.1 in February 1997 because they work unreliably across time zones. So even if you insisted on using Date (which I hope you don’t), you should still stay far away from the deprecated methods including all of the get methods except getTime (which converts to milliseconds since the epoch).
Link
Oracle tutorial: Date Time explaining how to use java.time.
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);
}
};
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");
}
}
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