Determine which day of week is each date of the month - java

I want to create a calendar with Java 8. So far I have this:
YearMonth yearMonthObject = YearMonth.of(year, month);
int daysOfCurrentMonth = yearMonthObject.lengthOfMonth();
int i = 1;
ArrayList<Integer> Dayes = new ArrayList<Integer>();
for(i=1; i<=daysOfCurrentMonth; i++){
Dayes.add(i);
}
Dayes.forEach(value -> System.out.print(value));
which prints the days of the current month (for example May).
How can I determine that 1 is Sunday, 2 is Monday, 3 is Tuesday, ..., 8 is Sunday (next week), etc.?

You have a YearMonth object. For each day of the month, you can call atDay(dayOfMonth) to return a LocalDate at that specific day of month. With that LocalDate, you can then call:
getDayOfMonth() to get back the day of the month as an int;
getDayOfWeek() to get the day of the week as a DayOfWeek. This is an enumeration of all the days of the week.
As such, you should change your Dayes list to hold LocalDates instead of Integers, and then you can have, for example:
YearMonth yearMonthObject = YearMonth.of(year, month);
int daysOfCurrentMonth = yearMonthObject.lengthOfMonth();
ArrayList<LocalDate> dayes = new ArrayList<LocalDate>();
for(int i = 1; i <= daysOfCurrentMonth; i++){
dayes.add(yearMonthObject.atDay(i));
}
dayes.forEach(value -> System.out.println(value.getDayOfMonth() + " " + value.getDayOfWeek()));
This will print each day of that month followed by the corresponding day of the week.
As a side-note, you can get a real display value for the day of week (instead of the name() of the enum like above) by calling getDisplayName(style, locale). The style represents how to write the days (long form, short form...) and the locale is the locale to use for the display name. An example would be:
value.getDayOfWeek().getDisplayName(TextStyle.FULL, Locale.ENGLISH)
which would output the full text of the day of the week in English. Sample output for 04/2016 with the above change:
1 Friday
2 Saturday
3 Sunday
4 Monday
5 Tuesday

This may be a bit of a 'hack' solution, but if you are trying to make a calendar for any year, you may have to use an 'anchor date' (Such as January 1, 1800 as a Wednesday). You then could calculate the number of days that happened between January 1st, 1800 and your current year/month/day. Once you figured out how many days have passed, using Modular 7 you could determine what day it is, and then populate the calendar for the month from there.

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.

Remaining years, months, days using joda time (Android)

I am trying to obtaining remaining years, months, and days between two dates:
So I have used Joda Time to do so:
DateTime endDate = new DateTime(2018,12,25,0,0);
DateTime startDate = new DateTime();
Period period = new Period(startDate,endDate,PeriodType.yearMonthDay());
PeriodFormatter formatter = new PeriodFormatterBuilder().appendYears().appendSuffix(" Year ").
appendMonths().appendSuffix(" Month ").appendDays().appendSuffix(" Day ").appendHours()..toFormatter();
String time = formatter.print(period);
This gives me string time: 2 Year 4 Month 22 Day
However, I want integer values of each number of remaining years, months, days.
So, Instead of "2 Year 4 Month 22 Day", I want to set my variables:
int year = 2
int month = 4
int day = 22
Is there any way to obtain these values separately instead of obtaining one string? Thank you so much! :)
i had the same requirement once ,here is the code snippet
LocalDate d=LocalDate.of(yy,mm,dd);
LocalDate d2=LocalDate.of(yy, mm, dd);
Period p=Period.between(d, d2);
long day,month,year;
day=p.getDays();
month=p.getMonths();
year=p.getYears();
System.out.println(day+" : "+month+" : "+year);
Invoke the methods provided by the DateTime class and just subtract them. An example for years is below:
int year = (int) dateTime#year#getField() - (int) dateTime2#year#getField()
UNTESTED code!! I'll be looking into it later but the general idea is the same, get the field information then just subtract it to get a value

Finding out what day the first of any given month is

So I need to make a basic calendar which displays the calendar for a specific year and month (the user should be able to select
any month and any year based on text input).
So far, I have managed to create a calender obj, use Scanner to get the desired month and year from the user but my question is that how do I find out what the first day of the month is? In the example above, it's a Saturday. My logic to building it is that if I know the first day, I can make a String[][] array and start displaying the day on the relevant date by looping through the month from the first day. I've used a scanner to get the required month and year. I then created a calendar object and set the Calendar variables; Calendar.YEAR and Calendar.MONTH, as per required by the user:
Calendar cal= Calendar.getInstance();
cal.set(Calendar.YEAR, year); //my year variable is set 2015
cal.set(Calendar.MONTH, chosenMonth); //my chosenMonth is set to 5 since January starts from 0.
I tried using the following code to test out my calender to see if it will execute the code if Monday was the first day of the month. On june 2015, it was.
if(cal.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY){
System.out.println("This will print is my calendar secessfully gathers that monday was the first day of the month on June 2015.")
}
It doesn't execute.
Try this:
cal.set(Calendar.DATE, 1);
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("EEEE");
System.out.println(sdf.format(cal.getTime()));
Output:
Saturday
Demo
Java SE 8 has a whole new API for date and time, java.time. See Tutorial.
You can use the class LocalDate to get the day of a given week. For example, using your day from above do,
LocalDate d = LocalDate.of(2011, 10, 1);
Then LocalDate::getDayOfWeek() method will return a DayOfWeek enum instance, such as SATURDAY.
DayOfWeek dayOfWeek = localDate.getDayOfWeek ();
That enum can render a localized string for your sentence output.
String output = dayOfWeek.getDisplayName ( TextStyle.FULL , Locale.CANADA_FRENCH); // Or Locale.US or Locale.ENGLISH, and so on.
samedi

finding the day based on date in java - gives incorrect answer

java.util.Date gives incorrect day as output.
java.util.Date date = new Date(2014,03,01);
System.out.println("day is" +date.getDay());
output : day is 3
actually it should be 7
Update : Thanks a lot I was able to get the output Here is my code
java.util.Calendar c = java.util.Calendar.getInstance();
c.clear();
c.set(year,month,dd);
System.out.println("day of week "+c.get(java.util.Calendar.DAY_OF_WEEK));
I guess you wanted to create the date March 1st 2014. But with your constructor call you create the date April 1st 3914!
The API tells you why:
A year y is represented by the integer y - 1900.
A month is represented by an integer from 0 to 11; 0 is January, 1 is February, and so forth; thus 11 is December.
A date (day of month) is represented by an integer from 1 to 31 in the usual manner.
EDIT: Also this constructor is deprecated. Use Calendar instead.
As per the javadoc of getDay()
Returns the day of the week represented by this date. The returned
value (0 = Sunday, 1 = Monday, 2 = Tuesday, 3 = Wednesday, 4 =
Thursday, 5 = Friday, 6 = Saturday) represents the day of the week
that contains or begins with the instant in time represented by this
Date object, as interpreted in the local time zone.
so its not day of month. Also note that you are using deprecated Date constructor and methods. You can achieve the same using java.util.Calendar
Also month 03 is not March, its April
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, 2014);
c.set(Calendar.MONTH, 3);
c.set(Calendar.DAY_OF_MONTH, 1);
System.out.println(c.get(Calendar.DAY_OF_WEEK));
Here also the output is 3 because, the date represents April 1st 2014, which is Tuesday and as per Calendar.DAY_OF_WEEK doc
Field number for get and set indicating the day of the week. This
field takes values SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY,
FRIDAY, and SATURDAY.
And Calendar.TUESDAY is 3

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.

Categories