How to get the months of the year in order - java

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

Related

Group list of Dates to week number? [Android]

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.

Calendar specified week keeps resetting

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?

Method to add Dates between 2 given dates?

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++
}

Disable past dates and 2 weeks from now in JCalendar

I want to disable past dates and 2 weeks from now from a JCalendar.
I already have this code:
jDateChooser1.getJCalendar().setMinSelectableDate(new Date());
((JTextFieldDateEditor)jDateChooser1.getDateEditor()).setEditable(false);
I already can disable past dates but how about disabling future dates like 2 weeks from now?
As shown here, you can use an IDateEvaluator like MinMaxDateEvaluator to invalidate a range of dates:
private static class RangeEvaluator extends MinMaxDateEvaluator {
#Override
public boolean isInvalid(Date date) {
return !super.isInvalid(date);
}
}
Then you can specify a range of invalid dates, e.g. a day before and two weeks after:
Calendar min = Calendar.getInstance();
min.add(Calendar.DAY_OF_MONTH, -1);
Calendar max = Calendar.getInstance();
max.add(Calendar.DAY_OF_MONTH, 13);
RangeEvaluator re = new RangeEvaluator();
re.setMinSelectableDate(min.getTime());
re.setMaxSelectableDate(max.getTime());
JCalendar jc = new JCalendar();
jc.getDayChooser().addDateEvaluator(re);
jc.setCalendar(jc.getCalendar());
Note that you can add multiple instances of RangeEvaluator to handle different ranges.
I haven't tried this but I imagine using a date in the future would do this:
Date d = new Date();
d.setTime(d.getTime() + 14 * 86400 * 1000); -- set the date 14 days forward
jDateChooser1.getJCalendar().setMinSelectableDate(d);
((JTextFieldDateEditor)jDateChooser1.getDateEditor()).setEditable(false);
Instead of working with a Date object and having to use setTime(milliseconds) you might want to use a proper Calendar object which has better methods for altering the date and so on.
Calendar cal = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_YEAR, 14);
Date twoweeks = calendar.getTime();
I already have answered my own question by the help of trashgod's code.
Here:
Calendar min = Calendar.getInstance();
min.add(Calendar.DAY_OF_MONTH, 15);
Calendar max = Calendar.getInstance();
max.add(Calendar.DAY_OF_MONTH, 2000000);
RangeEvaluator re = new RangeEvaluator();
re.setMinSelectableDate(min.getTime());
re.setMaxSelectableDate(max.getTime());
// JCalendar jc = new JCalendar();
jDateChooser1.getJCalendar().setMinSelectableDate(min.getTime());
jDateChooser1.getJCalendar().setMaxSelectableDate(max.getTime());
((JTextFieldDateEditor)jDateChooser1.getDateEditor()).setEditable(false);
Thanks! :D

How to get date of last Friday from specified date? [duplicate]

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('/');}

Categories

Resources