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.
Related
I have a function to return all dates for a specific week.
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM");
Calendar cal = Calendar.getInstance();
cal.set(Calendar.WEEK_OF_YEAR, week);
String[] dates = new String[7];
currentlySelectedYear = String.valueOf(Calendar.getInstance().get(Calendar.YEAR));
// i = 2 because MONDAY is day two in week
for (int i = 2; i < 9; i++) {
cal.set(Calendar.DAY_OF_WEEK, i);
//i-2 to start the array at index 0
dates[i - 2] = sdf.format(cal.getTime());
}
it works fine on all devices except samsung where each time the for loop is entered again after the first iteration the WEEK_OF_YEAR field in the calendar is reset to current week instead of the week set three lines above.
Is this a known bug for samsung or am I missing something?
Is there another way to do the same thing that maybe work on all devices?
This question already has answers here:
Get the number of weeks between two Dates.
(19 answers)
Closed 6 years ago.
My function should take start timestamp, end timestamp and entered date. Here, start and end timestamps could be anything (any timestamp).
This start timestamp and end timestamp will be of three week. If entered date falls in those timestamp range I need to get week of that date.
example:
start date - 06/08/2011 00:00:00
end Date - 26/08/2011 00:00:00
if entered date - 10/08/2011 This should return week number as 1
if entered date - 27/08/2011 This should return week number as 3.it has to take count of 7 days,from entered date and give the count of week.
Below is my code used.
import java.util.Calendar;
import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class LocaleTimeSample {
public static void main(String... args) {
try {
String dt = "";
String dt1 = "";
String dt2 = "";
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Calendar c = Calendar.getInstance();
sdf.setLenient(false);
String givenDateString = "02/06/2016";// given
String startDateString = "01/06/2016";// start
String endDateString = "21/06/2016";// end
Date givenDate = sdf.parse(givenDateString);
Date startDate = sdf.parse(startDateString);
Date endDate = sdf.parse(endDateString);
try {
c.setTime(sdf.parse(startDateString));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
c.add(Calendar.DAY_OF_MONTH, 7); // number of days to add
dt = sdf.format(c.getTime());
System.out.println("1 Week Date : " + dt);
Date date1 = (Date) sdf.parse(dt);
c.add(Calendar.DAY_OF_MONTH, 7); // number of days to add
dt1 = sdf.format(c.getTime());
System.out.println("2 Week Date : " + dt1);
Date date2 = (Date) sdf.parse(dt1);
c.add(Calendar.DAY_OF_MONTH, 7); // number of days to add
dt2 = sdf.format(c.getTime());
System.out.println("2 Week Date : " + dt2);
Date date3 = (Date) sdf.parse(dt2);
if (givenDate.compareTo(date1) <= 0) {
System.out.println("Week 1");
} else if (givenDate.compareTo(date2) <= 0
&& givenDate.compareTo(date1) > 0) {
System.out.println("Week 2");
} else if (givenDate.compareTo(date3) <= 0
&& givenDate.compareTo(date2) > 0) {
System.out.println("Week 3");
}
} catch (ParseException pe) {
pe.printStackTrace();
}
}
}
Can anybody help me to minimixe the code of line and reusability apprach where were needed.
Any idea regarding this is appreciated.
Convert to Date or Calendar and retreive the field you need
Assumming your Date is String this is what you must do to convert it to Date and Calendar
String startDate = "06/08/2011 00:00:00";
DateFormat format = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
Date startDateasDate = format.parse(startDate);
Calendar cal = Calendar.getInstance();
cal.setTime(startDateasDate);
Then you can retrieve wichever date you want with the proper flag:
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
int weekOfYear = cal.get(Calendar.WEEK_OF_YEAR);
Here you can see a list of the available flags:
https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html
Convert the start date, end date and input date to LocalDateTime
Check that the entered date is after the start date and before the end date. You can use LocalDateTime.isBefore and isAfter for this.
Use LocalDateTime.until with TemporalUnit set to weeks to calculate the amount of weeks from the start date to the entered date. You can then add 1 to this result to get the week number (0 amount of weeks = week 1, 1 amount of weeks = week 2 and so on)
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++
}
I went to display the current date and the six (6) last dates
example :
02/11/2012
01/11/2012
31/10/2012
30/10/2012
29/10/2012
28/10/2012
to get the current day in JAVA I used :
Date date = Calendar.getInstance().getTime();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
System.out.println("current day : "+sdf.format(date));
but how do I decrement the days ?
You can use the Calendar#add method to substract a day, like:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
Calendar cal = Calendar.getInstance();
Date date=cal.getTime();
System.out.println(sdf.format(date)); //remove line to display only the last 5 days
for (int i=0;i<5;i++){
cal.add(Calendar.DAY_OF_MONTH,-1);
date=cal.getTime();
System.out.println(sdf.format(date));
}
Like Jon Skeet (soon Mr. 500k :) ) suggested, I too find the Joda Time API more cleaner and appropriate, even for such simple tasks:
DateTime dt = new DateTime();
for (int i = 0; i < 6; i++) {
System.out.println(dt.toString("yyyy/MM/dd"));
dt = dt.minusDays(1);
}
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
System.out.println("current day : "+sdf.format(c.getTime()));
// decrement 1 day
c.add(Calendar.DAY_OF_MONTH, -1);
// getTime() returns a java.util.Date
System.out.println("the day before : "+sdf.format(c.getTime()));
// getTimeInMillis() returns a long, which can be used to construct a java.sql.Date
System.out.println("the day before : "+sdf.format(new java.sql.Date(c.getTimeInMillis()));
And so on...
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