Getting range of months - Java - java

I want to implement a tab layout with a range of months. This range should contain the last and next 12 Months.
I know how to get the next 12 months but i stuck at how to get the last AND next 12 months. I could use the joda time library but i think this lib is too big for my small android application.
Can anybody help my by providing a small code snipped? Thanks!

You can simply use a Calendar class instance to do it, with Calendar#add(int field,
int amount) like:
//getting month names
DateFormatSymbols dfs = new DateFormatSymbols();
String[] months = dfs.getMonths();
//here is what you need
Calendar c = Calendar.getInstance();
System.out.println(c.getTime().toString());
c.add(Calendar.MONTH, -12);
for (int i = -12; i <=12; i++){
c.add(Calendar.MONTH, +1);
System.out.println(months[c.get(Calendar.MONTH)]);
}
DateFormatSymbols is here used, to get the names of the months only.

You can use the calendar class to get the current month. Then u can subtract 1 to get the value of last month or add 1 to get next month.
Here is an example snippet.
Calendar calendar = Calendar.getInstance();
int month = calendar.get(Calendar.MONTH);
calendar.set(Calendar.MONTH, month - 1);
int lastMonth = calendar.get(Calendar.MONTH);
U could write a loop to calculate last and next 12 months this way.
Cheers :)

Related

Time manipulation by -1 month +1 day is still 1 month difference from start

I would like to reach date that is -1month +1day, which should be 0month difference from start date.
Using joda-time 2.10:
int day = 29;
LocalDate date1 = new LocalDate(new GregorianCalendar(2019, Calendar.JUNE, day).getTime());
LocalDate date2 = date1.plusMonths(-1).plusDays(1);
Months.monthsBetween(date1,date2).getMonths(); // returns 0 <- it's OK
but the same code with input int day = 30; returns -1 which is bad.
That looks like an inconsequence in Joda library.
That's a case: shift by -1month change date by shift month number and keep day number no greater than in input, but month-difference between dates are depend on day of month.
Do you know any alternative and working solution?
I have found JSR-310 with ChronoUnit - that solves the problem, BUT it needs Java8. I would like to stay on Java7.

Android , Calendar.getInstance() not giving the correct month

I am trying to write code to find the Day difference between tow date but Calendar.getInstance() keep getting the date for previous month instead of current month
for example :Current 17/7/2014 it get 17/6/2014
my code :
TextView textview=(TextView) findViewById (R.id.textView1);
Calendar cal = Calendar.getInstance();
Calendar startDate=Calendar.getInstance();
startDate.set(Calendar.DAY_OF_MONTH, 1);
startDate.set(Calendar.MONTH,1);
startDate.set(Calendar.YEAR, 2013);
long diff=(((cal.getTimeInMillis()-startDate.getTimeInMillis())/(1000*60*60*24))+1);
String sdiff=String.valueOf(diff);
String stt=cal.get(Calendar.YEAR) +"_"+cal.get(Calendar.MONTH)+"_"+cal.get(Calendar.DAY_OF_MONTH);
textview.setText(stt);
Months start at 0, not at 1, but you really don't have to worry about this if you don't use magic numbers when getting or setting month but instead use the constants. So not this:
startDate.set(Calendar.MONTH,1); // this is February!
but rather
startDate.set(Calendar.MONTH, Calendar.JANUARY);
Months in Java's Calendar start with 0 for January, so July is 6, not 7.
Calendar.MONTH javadocs:
The first month of the year in the Gregorian and Julian calendars is JANUARY which is 0
Add 1 to the result of get.
(cal.get(Calendar.MONTH) + 1)
This also affects your set call. You can either subtract 1 when passing a month number going in, or you can use a Calendar constant, e.g. Calendar.JANUARY.
You can also use a SimpleDateFormat to convert it to your specific format, without having to worry about this quirk.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd");
String stt = sdf.format(cal.getTime());

How to use JCalendar to select an element of my array?

I have a 3D array that contains 38 years, 12 months, and 31 entries for each month (regardless of how many days in that month). Like so: array[38][12][31]. I also have a JCalendar that is doing nothing now except looking pretty, and the JCalendar has a button underneath. How would I make it so that I can select a date in the calendar, then press the button and it returns the element of my array that would correspond to that date?
Something like
if(buttonPressed){
year = chosenYear - 1975;
month = chosenMonth;
day = chosenDay;
System.out.print(array[year][month][day]);
}
thanks guys.
You can get the selected Date in a PropertyChangeListener, as shown here. Once you have the date, you can get the year, month and day from a Calendar:
Calendar c = Calendar.getInstance();
c.setTime(date);
int y = c.get(Calendar.YEAR);
int m = c.get(Calendar.MONTH);
int d = c.get(Calendar.DAY_OF_MONTH);
Calendar.MONTH is already zero-based, but Calendar.DAY_OF_MONTH is not; and you'll need to adjust the year to your baseline.

Android Calendar: Changing the start day of week

i have a little problem, i'm developing an application, and i need to change the start day of the week from monday to another one (thursday, of saturday). is this possible in android,
i need to calculate the start to week and its end knowing the date. (the week starts ano thursday as example)
Note: i'm just a beginner in android development.
here is my code
SimpleDateFormat dateformate = new SimpleDateFormat("dd/MM");
// get today and clear time of day
Calendar cal = Calendar.getInstance();
// get start of this week in milliseconds
cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
cal.add(Calendar.DAY_OF_YEAR, 7*(WeekIndex-1));
result = dateformate.format(cal.getTime());
cal.add(Calendar.DAY_OF_YEAR, 6 );
result=result+" - " + dateformate.format(cal.getTime());
using the above code im getting the result but with monday as the star of week.
Note: i can't add day to the result because week index changes with the changing of it's start
Calendar days have values 1-7 for days Sunday-Saturday. getFirstDayOfWeek returns one of this values (usually of Monday or Sunday) depending on used Locale. Calendar.getInstance uses default Locale depening on phone's settings, which in your case has Monday as first day of the week.
One solution would be to use other Locale:
Calendar.getInstance(Locale.US).getFirstDayOfWeek()
would return 1, which is value of Calendar.SUNDAY
Other solution would be to use chosen day of week value like
cal.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
Problem is, Calendar is using its inner first day of the week value in set as well. Example:
Calendar mondayFirst = Calendar.getInstance(Locale.GERMANY); //Locale that has Monday as first day of week
mondayFirst.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
log(DateUtils.formatDateTime(context, mondayFirst.getTimeInMillis(), 0));
//prints "May 19" when runned on May 13
Calendar sundayFirst = Calendar.getInstance(Locale.US); //Locale that has Sunday as first day of week
sundayFirst.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
log(DateUtils.formatDateTime(context, sundayFirst.getTimeInMillis(), 0));
//prints "May 12" when runned on May 13
If you don't want to use Locale or you need other day as the first day of the week, it may be best to calculate start of the week on your own.
GregorianCalendar cal = new GregorianCalendar(yy, currentMonth, 0);
changing the value 0 - starts day from monday
changing the value 1 - starts day from sunday
and so on..
hope this helps and works :)
public int getWeekdayOfMonth(int year, int month){
Calendar cal = Calendar.getInstance();
cal.set(year, month-1, 1);
dayOfWeek = cal.get(Calendar.DAY_OF_WEEK)-1;
return dayOfWeek;
}
weekday = getWeekdayOfMonth();
int day = (weekday - firstweek) < 0 ? (7 - (firstweek - weekday)) : (weekday - firstweek);
"firstweek" means what the start day of you want
then you can calculate the first day you should show.If you have simple method,please tell us. thks
Problem in my case was using Calendar instance returned by MaterialDialog DatePicker, which although having the same Locale as my Calendar.getInstance(Locale...), was having different Calendar.firstDayOfWeek. If you're experiencing the same issue, my workaround was to create new instance of Calendar with my Locale and just changing the property time to the one returned by the DatePicker as following:
val correctCal = Calendar.getInstance(Locale...)?.apply {
time = datePickerCal.time
}
This should return proper Calendar.firstDayOfWeek based on your Locale.

Android: compare calendar dates

In my app I´m saving when I last updated some data from my server.
Therefore I used:
long time = Calendar.getInstance().getTimeInMillis();
Now I want that the data is updated twice a year at 03.03 and 08.08.
How can I check wheater one of these two date boarders were crossed since last update?
Change them to time in mseconds and compare:
Calendar c = Calendar.getInstance();
c.set(Calendar.MONTH, Calendar.MARCH);
c.set(Calendar.DAY_OF_MONTH, 3);
long time2= c.getTimeInMillis();
c.set(Calendar.MONTH, Calendar.AUGUST);
c.set(Calendar.DAY_OF_MONTH, 8);
long time3= c.getTimeInMillis();
if(time>time2){
//Logic
if(time>time3){
//Logic
}
}
There is something very important which took me a while to figure it out and can be very helpful to people out there, if you are looking for an answer to any of the following questions this is for you:
Why is my date not showing correctly?
Why even when I set the time manually it is not showing right?
Why is the month and the year showing one day less than the one that I set?
For some reason Java sorts the months values like an array, what I mean is that for Java January is 0 and DECEMBER is 11. Same happens for the year, if you set December as month 12 and year as 2012, and then try to do a "system.out.println" of the month and the year, it will show my month as January and the year as 2013!!
so what should you do?
Calendar cal = new GregorianCalendar();
cal.set(2012, 11, 26); // the date I want to input is 26/12/2012 (for Java, 11 is December!)
NOW WHAT IS THE CORRECT WAY TO GET THAT DATE TO SEE IT ON THE SCREEN?
if you try to "system.out.println of yourCalendar.DATE, yourCalendar.MONTH and yourCalendar.YEAR," THAT WILL NOT SHOW YOU THE RIGHT DATE!!!!
If you want to display the dates you need to do the following:
System.out.println (calact.get (calact.DATE));
// displays day
System.out.println (calact.get (calact.MONTH)+1);
//add 1 remember it saves values from 0-11
System.out.println (calact.get (calact.YEAR));
// displays year
NOW IF YOU ARE HANDLING STRINGS THAT REPRESENT DATES, OR....
IF YOU NEED TO COMPARE DATES BETWEEN RANGES , LET'S SAY YOU NEED TO KNOW IF DATE "A" WILL TAKE PLACE WITHIN THE NEXT 10 DAYS....THIS....IS.....FOR....YOU!!
In my case I was working with a string that had format "15/07/2012", I needed to know if that date would take place within the next 10 days, therefore I had to do the following:
1 get that string date and transform it into a calendar ( StringTokenizer was used here )
this is very simple
StringTokenizer tokens=new StringTokenizer(myDateAsString, "/");
do nextToken and before returning the day, parse it as integer and return it.
Remember for month before returning substract 1.
I will post the code for the first you create the other two:
public int getMeD(String fecha){
int miDia = 0;
String tmd = "0";
StringTokenizer tokens=new StringTokenizer(fecha, "/");
tmd = tokens.nextToken();
miDia = Integer.parseInt(tmd);
return miDia;
}
2 THEN YOU CREATE THE CALENDAR
Calendar cal = new GregorianCalendar(); // calendar
String myDateAsString= "15/07/2012"; // my Date As String
int MYcald = getMeD(myDateAsString); // returns integer
int MYcalm = getMeM(myDateAsString); // returns integer
int MYcaly = getMeY(myDateAsString); // returns integer
cal.set(MYcaly, MYcalm, MYcald);
3 get my current date (TODAY)
Calendar curr = new GregorianCalendar(); // current cal
calact.setTimeInMillis(System.currentTimeMillis());
4 create temporal calendar to go into the future 10 days
Calendar caltemp = new GregorianCalendar(); // temp cal
caltemp.setTimeInMillis(System.currentTimeMillis());
caltemp.add(calact.DAY_OF_MONTH, 10); // we move into the future
5 compare among all 3 calendars
here basically you ask if the date that I was given is for sure taking place in the future AND (&&) IF the given date is also less than the future date which had 10 days more, then please show me "EVENT WILL TAKE PLACE FOR SURE WITHIN THE NEXT 10 DAYS!!" OTHERWISE SHOW ME:
"EVENT WILL NOT TAKE PLACE WITHIN THE NEXT 10 DAYS".
if((cal.getTimeInMillis() > curr.getTimeInMillis()) && (cal.getTimeInMillis()< curr.getTimeInMillis()))
{ System.out.println ("EVENT WILL TAKE PLACE FOR SURE WITHIN THE NEXT 10 DAYS!!");}
else
{ System.out.println ("EVENT WILL *NOT* TAKE PLACE WITHIN THE NEXT 10 DAYS");}
ALRIGHT GUYS AND GIRLS I HOPE THAT HELPS. A BIG HUG FOR YOU ALL AND GOOD LUCK WITH YOUR PROJECTS!
PEACE.
YOAV.
If the comparison should involve only the year, month and day then you can use this method for check if c1 is before c2. Ugly, but works.
public static boolean before(Calendar c1, Calendar c2){
int c1Year = c1.get(Calendar.YEAR);
int c1Month = c1.get(Calendar.MONTH);
int c1Day = c1.get(Calendar.DAY_OF_MONTH);
int c2Year = c2.get(Calendar.YEAR);
int c2Month = c2.get(Calendar.MONTH);
int c2Day = c2.get(Calendar.DAY_OF_MONTH);
if(c1Year<c2Year){
return true;
}else if (c1Year>c2Year){
return false;
}else{
if(c1Month>c2Month){
return false;
}else if(c1Month<c2Month){
return true;
}else{
return c1Day<c2Day;
}
}
}
used compareTo method ..and this returns integer value .if returns -ve the days before in current date else return +ve the days after come current date

Categories