I'm working on a method that can add dates like this :
public static ArrayList<Calendar> addDaysBetween(Calendar day1, Calendar day2)
Which returns the ArrayList containing all the dates between d1 & d2.
So, first I needed to know how many days exists between those two dates (Followed this example : https://stackoverflow.com/a/28865648/4944071)
I wrote something like this :
ArrayList<Calendar> fullDates = new ArrayList<Calendar>();
if(daysBetween > 0){
for(int day = 1; day <= daysBetween; day ++){
Calendar aNewDay = new GregorianCalendar(day1.YEAR, day1.MONTH, day1.DAY_OF_MONTH + day);
fullDates.add(aNewDay);
}
}
But, I'm pretty sure that this will not work at all. Imagine those parameters :
2012/12/21 to 2013/02/14
Not the same year, not the same month, It can't work properly. So, I scratched my head a little bit and decided to use the variable DAY_OF_YEAR.
But, i'm still stuck because I don't know how I could manipulate this variable to create correct dates with good Months & good Years..
You can try this
Calendar tmp = (Calendar) day1.clone();
ArrayList<Calendar> fullDates = new ArrayList<Calendar>();
while (tmp.before(day2)) {
fullDates.add((Calendar) tmp.clone());
tmp.add(Calendar.DAY_OF_MONTH, 1);
}
return fullDates;
With the java8 date api:
List<LocalDate> listOfDates = new ArrayList<>();
LocalDate endDay = LocalDate.of(2014, Month.JUNE, 20);
LocalDate startDay = LocalDate.of(2014, Month.JUNE, 11);
long days = ChronoUnit.DAYS.between(startDay, endDay);
for (int i = 1; i <= days; i++) {
listOfDates.add(startDay.plusDays(i));
}
if you want to convert to java.util.Date or Calendar:
Date d = Date.from(startDay.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
Calendar cal = Calendar.getInstance();
cal.setTime(d);
Try something like:
currentDay = day1;
while (currentDay < day2){
addcurrentday to collection
currentday++
}
Related
I am working on an android app that will display a list of data. For example, if you start to use app today(28.05.2018)(MO) and I must calculate week number and add 7 days this week or you are starting Friday I must add 2 days this week.
I tried this method https://stackoverflow.com/a/42733001/9259044
but its wrong for me. First of all, I added dates and
TreeMap<Integer, List<Date>> dateHashMap = new TreeMap<>();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
List<Date> spDates = new ArrayList<>();
try {
spDates.add(sdf.parse("02/06/2018"));
spDates.add(sdf.parse("01/06/2018"));
spDates.add(sdf.parse("31/05/2018"));
spDates.add(sdf.parse("30/05/2018"));
spDates.add(sdf.parse("29/05/2018"));
spDates.add(sdf.parse("28/05/2018"));
spDates.add(sdf.parse("27/05/2018"));
spDates.add(sdf.parse("26/05/2018"));
spDates.add(sdf.parse("25/05/2018"));
} catch (ParseException e) {
e.printStackTrace();
}
I compare weekOfYear to my dates but this is wrong.
for (int i = 0; i < spDates.size(); i++) {
List<Date> datesList = new ArrayList<>();
Calendar calendar = Calendar.getInstance();
calendar.setTime(spDates.get(i));
int weekOfYear = calendar.get(Calendar.WEEK_OF_YEAR);
for (Date date : spDates) {
Calendar c = Calendar.getInstance();
c.setTime(date);
if (weekOfYear == c.get(Calendar.WEEK_OF_YEAR)) {
datesList.add(date);
}
}
dateHashMap.put(weekOfYear, datesList);
}
Log.d("DATE",dateHashMap.toString());
Do you have any idea how can I group my Dates to week Number?
I think you want this:
LocalDate today = LocalDate.now(ZoneId.of("Europe/Istanbul"));
int weekNumber = today.get(WeekFields.ISO.weekOfYear());
System.out.println("Week no. " + weekNumber);
LocalDate[] days = today.datesUntil(today.with(TemporalAdjusters.next(DayOfWeek.MONDAY)))
.toArray(LocalDate[]::new);
System.out.println(Arrays.toString(days));
Running it today (Monday, May 28) it printed
Week no. 22
[2018-05-28, 2018-05-29, 2018-05-30, 2018-05-31, 2018-06-01, 2018-06-02, 2018-06-03]
It gives you all the dates from today, inclusive, until next Monday, exclusive. If Monday is the first day of the week, this means the remaining days of this week.
I'm new to Java. I have this code which is used to get the days of the week starting of the current.
GregorianCalendar calendar = new GregorianCalendar();
DateFormat df = new SimpleDateFormat("EEEE");
for (int i = 0; i < 7; i++) {
calendar.add(Calendar.DATE, 1);
System.out.println(df.format(calendar.getTime()));
}
I want edit the code to get the months of the year in the same way - starting from the present month. Can you help me to edit the code.
Well, you could set the day of the month to 1 (just for sanity) and then just add a month on each step instead of a day. Alternatively, you could just use:
DateFormatSymbols symbols = new DateFormatSymbols(locale);
String[] months = symbols.getMonths();
... and go from there.
You could use getWeekdays in the same way for the day names, too.
You can use Calendar.MONTH. With minimal changes to your code, it'll look like this:
GregorianCalendar calendar = new GregorianCalendar();
DateFormat df = new SimpleDateFormat("MMMM");
for (int i = 0; i < 12; i++) {
calendar.add(Calendar.MONTH, 1);
System.out.println(df.format(calendar.getTime()));
}
In JodaTime you can do new DateTime() and then do plusMonths(1) to add one month. This will return the date one month on. You can then parse that to get the month. Then repeat 11 times to get the rest of the months.
This link will help to get the month name http://joda-time.sourceforge.net/key_instant.html
I would like to ask what is the most suitable way to create List of Dates for specific year to hold the dates of this year.
I have written the following and it works fine.
However,I am not sure that this the most convenient way.
Calendar cal = new GregorianCalendar(2012, Calendar.JANUARY, 1);
Date startDate = cal.getTime();
cal = new GregorianCalendar(2013, Calendar.JANUARY, 1);
Date endDate = cal.getTime();
List<Date> dates = new ArrayList<Date>();
Calendar calendar = new GregorianCalendar();
calendar.setTime(startDate);
while (calendar.getTime().before(endDate)) {
Date date= calendar.getTime();
dates.add(date);
calendar.add(Calendar.DATE, 1);
}
You could just simplify that:
int startYear = 2012;
int endYear = 2013;
Calendar cal = new GregorianCalendar(startYear, Calendar.JANUARY, 1);
ArrayList<Date> dates = new ArrayList<Date>();
while(cal.get(Calendar.YEAR) < endYear){
dates.add(cal.getTime());
cal.add(Calendar.DATE, 1);
}
Similar as how to get a list of dates between two dates in java
With Lamma one can easily construct date range:
for (Date d: Dates.from(2014, 6, 29).to(2014, 7, 1).build()) {
System.out.println(d);
}
And the output is:
Date(2014,6,29)
Date(2014,6,30)
Date(2014,7,1)
The user entered date is using a drop down separately for day, month and year. I have to compare the user entered date with today's date and check if it is same day or future day. I am a bit confused about the time portion because I am not interested in time, just the date. How to solve this without using the Date class (I read it is not recommended to use Date class).
Thanks.
You first need to create GregorianCalendar instance representing entered date:
Calendar user = new GregorianCalendar(2012, Calendar.MAY, 17);
And one for "now":
Calendar now = new GregorianCalendar();
This will yield positive value if date is in the future and negative - if in the past:
user.compareTo(now);
Few notes about constructing user object:
it uses current JVM time zone, so in my case it is midnight, 17th of May in CEST time zone
be careful with months, they are 0-based
Try class DateUtils of library Apache Commons Lang.
This class provides the method truncatedEquals(cal1, cal2, field).
So you can check for equality with a single line of code:
Calendar user = new GregorianCalendar(2012, Calendar.MAY, 17);
Calendar now = Calendar.getInstance();
if(DateUtils.truncatedEquals(user, now, Calendar.DATE)){
// your code goes here
}
Simple calculation :
GregorianCalendar gc1 = new GregorianCalendar();
GregorianCalendar gc2 = new GregorianCalendar();
gc2.add(GregorianCalendar.DAY_OF_MONTH, 2); // gc2 is 2 days after gc1
long duration = (gc2.getTimeInMillis() - gc1.getTimeInMillis() )
/ ( 1000 * 60 * 60 * 24) ;
System.out.println(duration);
-> 2
Use a gregorian calendar.
If you wanted to know the number of days difference between two dates then you could make a method similar to the following.
public int getDays(GregorianCalendar g1, GregorianCalendar g2) {
int elapsed = 0;
GregorianCalendar gc1, gc2;
if (g2.after(g1)) {
gc2 = (GregorianCalendar) g2.clone();
gc1 = (GregorianCalendar) g1.clone();
}
else {
gc2 = (GregorianCalendar) g1.clone();
gc1 = (GregorianCalendar) g2.clone();
}
gc1.clear(Calendar.MILLISECOND);
gc1.clear(Calendar.SECOND);
gc1.clear(Calendar.MINUTE);
gc1.clear(Calendar.HOUR_OF_DAY);
gc2.clear(Calendar.MILLISECOND);
gc2.clear(Calendar.SECOND);
gc2.clear(Calendar.MINUTE);
gc2.clear(Calendar.HOUR_OF_DAY);
while ( gc1.before(gc2) ) {
gc1.add(Calendar.DATE, 1);
elapsed++;
}
return elapsed;
}
That would return you the difference in the number of days.
Try this solution:
int day = 0; //user provided
int month = 0; //user provided
int year = 0; //user provided
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONDAY, month);
calendar.set(Calendar.DAY_OF_MONTH, day);
long millisUser = calendar.getTime().getTime();
long nowMillis = System.currentTimeMillis();
if(nowMillis < millisUser) {
...
}
Above is check if date is in future.
There is nothing wrong in using java.util.Date
You can use:
int day = 0; //user provided
int month = 0; //user provided
int year = 0; //user provided
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONDAY, month);
calendar.set(Calendar.DAY_OF_MONTH, day);
Date userSubmit = calendar.getTime();
Date now = new Date();
if(userSubmit.after(now)) {
...
}
But if you want fluent, easy and intuitive API with dates I recommend using JodaTime
This question already has answers here:
Time: How to get the next friday?
(9 answers)
Closed 6 years ago.
How can I find out the date of last (previous) "Friday" or any other day from a specified date?
public getDateOnDay(Date date, String dayName) {
// ?
}
I won't give an answer (try it yourself first!), but, maybe these tips can help you out.
You first need to figure out the current day of the week you are on. You may want to take a look at Java's Calendar class to get an idea of how to do that.
Once you get the date you are on, think about the modulus operator and how you can use that to move backwards to pick up the previous day that you are looking for from the day you are currently at. (Remember, a week is 7 days and each day of the week takes up a "slot" in those 7 days.)
Once you have the number of days in between, you'll want to subtract. Of course, there are classes that can add and subtract days for you in the Java framework...
I hope that helps. Again, I encourage you to always try the problem for yourself, first. You learn far much more that way and be a better developer in the long run for it.
Here is a brute force idea. Check if current date is friday. If not, subtract 1 day from today. Check if new date is friday. If not, subtract 1 day from new date..... so on.. you get the idea.
Try this one:
/**
* Return last day of week before specified date.
* #param date - reference date.
* #param day - DoW field from Calendar class.
* #return
*/
public static Date getDateOnDay(Date date, int day) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.WEEK_OF_YEAR, -1);
cal.set(Calendar.DAY_OF_WEEK, day);
return cal.getTime();
}
Good luck.
I'm using this:
private Date getDateOnDay(Date date, int day) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.setFirstDayOfWeek(day);
cal.set(Calendar.DAY_OF_WEEK, day);
return cal.getTime();
}
Get the day of week for the date. Look at Calendar javadoc. Once you have the day of the week you can calculate an offset to apply to the date.
To get any latest date based on weekday:
private String getWeekDayDate(String weekday){
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Calendar start = Calendar.getInstance();
Date now = new Date();
start.setTime(now);
Calendar end = Calendar.getInstance();
end.add(Calendar.DATE, -7);
while (start.after(end))
{
try {
Date temp = start.getTime();
String day = new SimpleDateFormat("EEEE").format(temp);
if(day.equalsIgnoreCase(weekday))
return formatter.format(temp);
}catch(Exception e) {
e.printStackTrace();
}
start.add(Calendar.DAY_OF_YEAR, -1);
}
return null;
}
To get latest Friday date, give weekday as "Friday"
//gets the last four Fridays from today's date if you want pass in a any date
//just need to tweak the code, the other method just basically formats the date in dd/MM/YYYY format.
function GetLastFourFridays() {
today = new Date();
LastFridayDate = new Date();
LastFridayDate.setDate(LastFridayDate.getDate() - 1);
while (LastFridayDate.getDay() != 5) {
LastFridayDate.setDate(LastFridayDate.getDate() - 1);
}
var lfd = LastFridayDate
lfd = convertDate(lfd)
document.getElementById("first_week_th").innerHTML = lfd
LastFridayDate.setDate(LastFridayDate.getDate() - 1);
var friLastWeek = LastFridayDate
while (friLastWeek.getDay() != 5) {
friLastWeek.setDate(friLastWeek.getDate() - 1);
}
var flw = friLastWeek
flw = convertDate(flw)
document.getElementById("second_week_th").innerHTML = flw
friLastWeek.setDate(friLastWeek.getDate() - 1);
var friTwoWeeks = friLastWeek
while (friTwoWeeks.getDay() != 5) {
friTwoWeeks.setDate(friTwoWeeks.getDate() - 1);
}
var ftw = friTwoWeeks
ftw = convertDate(ftw)
document.getElementById("third_week_th").innerHTML = ftw
friTwoWeeks.setDate(friTwoWeeks.getDate() - 1);
var friThreeWeeks = friTwoWeeks
while (friThreeWeeks.getDay() != 5) {
friThreeWeeks.setDate(friThreeWeeks.getDate() - 1);
}
var ftww = friThreeWeeks
ftww = convertDate(ftww)
document.getElementById("fourth_week_th").innerHTML = ftww
}
//convets the date 00//00//0000
function convertDate(inputFormat) {
function pad(s) { return (s < 10) ? '0' + s : s; }
var d = new Date(inputFormat);
return [pad(d.getDate()), pad(d.getMonth()+1), d.getFullYear()].join('/');}