Finding out what day the first of any given month is - java

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

Related

I want to get last date of the month and add n months to it but calendar instance is taking only 30 days in Java

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar calender = Calendar.getInstance();
calender.set(Calendar.DAY_OF_MONTH, calender.getActualMaximum(Calendar.DATE));
int months = 1;
calender.add(Calendar.MONTH, months );
String time = sdf .format(calender .getTime());
System.out.println(time);
Since current month is April and last date is 2020-04-30
Next month last date I should get 2020-05-31
but I am getting last date as 2020-05-30
Any thing am i doing wrong ?
java.time
I recommend that you use java.time, the modern Java date and time API, for your date work. It’s much nicer to work with than the old classes Calendar and SimpleDateFormat.
LocalDate endOfNextMonth =
YearMonth // Represent an entire month in a particular year.
.now(ZoneId.of("Europe/Volgograd")) // Capture the current year-month as seen in a particular time zone. Returns a `YearMonth` object.
.plusMonths(1) // Move to the next month. Returns another `YearMonth` object.
.atEndOfMonth(); // Determine the last day of that year-month. Returns a `LocalDate` object.
String time = endOfNextMonth.toString(); // Represent the content of the `LocalDate` object by generating text in standard ISO 8601 format.
System.out.println("Last day of next month: " + time);
Output when running today:
Last day of next month: 2020-05-31
A YearMonth, as the name maybe says, is a year and month without day of month. It has an atEndOfMonth method that conveniently gives us the last day of the month as a LocalDate. A LocalDate is a date without time of day, so what we need here. And its toString method conveniently gives the format that you wanted (it’s ISO 8601).
Depending on the reason why you want the last day of another month there are a couple of other approaches you may consider. If you need to handle date ranges that always start and end on month boundaries, you may either:
Represent your range as a range of YearMonth objects. Would this free you from knowing the last day of the month altogether?
Represent the end of your range as the first of the following month exclusive. Doing math on the 1st of each month is simpler since it is always day 1 regardless of the length of the month.
What went wrong in your code?
No matter if using Calendar, LocalDate or some other class you need to do things in the opposite order: first add one month, then find the end of the month. As you know, months have different lengths, so the important part is getting the end of that month where you want to get the last day. Putting it the other way: setting either a LocalDate or a Calendar to the last day of the month correctly sets it to the last day of the month in qustion but does not instruct it to stay at the last day of the month after subsequent changes to its value, such as adding a month. If you add a month to April 29, you get May 29. If you add a month to April 30, you get May 30. Here it doesn’t matter that 30 is the last day of April while 30 is not the last day of May.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Wikipedia article: ISO 8601
You'd better use LocalDate like this:
LocalDate now = LocalDate.now();
LocalDate lastDay = now.withDayOfMonth(now.lengthOfMonth());
LocalDate nextMonth = lastDay.plusMonths(1);
Don't use deprecated classes from java.util.*.
Use classes from java.time.*.
Example with LocalDate :
public class Testing {
public static void main(String args[]) {
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate date = LocalDate.now();
int months = 1;
date = date.plusMonths(months);
date = date.withDayOfMonth(date.lengthOfMonth());
System.out.println(date.format(dateTimeFormatter));
}
}
Output :
2020-05-31
Example with Calendar :
public class Testing {
public static void main(String args[]) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar calender = Calendar.getInstance();
int months = 1;
calender.add(Calendar.MONTH, months);
calender.set(Calendar.DAY_OF_MONTH, calender.getActualMaximum(Calendar.DAY_OF_MONTH));
String time = sdf.format(calender.getTime());
System.out.println(time);
}
}
Output :
2020-05-31

Determine which day of week is each date of the month

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.

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());

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.

Get Current Day (Monday, Tuesday, etc) in Java

I am working on a program that asks the user which day they would like to see a lunch menu for. They can enter any day by name (Monday, Tuesday, etc.). This works well, but I would also like them to be able to enter "Today" and then have the program get the current date and then check the menu for that value.
How would I do this?
You can use java.util.Calendar:
Calendar calendar = Calendar.getInstance();
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
This is the exact answer of the question,
Calendar calendar = Calendar.getInstance();
Date date = calendar.getTime();
System.out.println(new SimpleDateFormat("EE", Locale.ENGLISH).format(date.getTime()));
System.out.println(new SimpleDateFormat("EEEE", Locale.ENGLISH).format(date.getTime()));
Result (for today):
Sat
Saturday
As of Java 8 and its new java.time package:
DayOfWeek dayOfWeek = DayOfWeek.from(LocalDate.now());
or
DayOfWeek dayOfWeek = LocalDate.now().getDayOfWeek();
Java 8 :
LocalDate.now().getDayOfWeek().name()

Categories