4

I want to detect date of First Sunday/Monday of first/second week in every month in java? How can I achieve it?

I have checked Calendar class as well as Date class in java but not able to get solution for that so please help me out for this.

suspectus
  • 16,548
  • 8
  • 49
  • 57
user2990781
  • 41
  • 1
  • 3
  • try my answer it will give you first monday of every month in a year – vipul mittal Jan 21 '14 at 18:40
  • Hello Vipul,Your code working very fine.Thanks a lot for help.But it is just giving me the First Monday of month only.Actually What i want is it should return me the first Monday of First week/Second week/Third Week accordingly. – user2990781 Jan 22 '14 at 07:40
  • Hello Vipul,Your Updated answer giving me the dates of first week only.What I want is all the dates for Monday in current month.e.g. it should return me 6,13,20,27 January as value. – user2990781 Jan 22 '14 at 16:59
  • you want all the dates for all the mondays?? – vipul mittal Jan 22 '14 at 17:20
  • check my edit this should give all the mondays in 2014 – vipul mittal Jan 22 '14 at 17:25

7 Answers7

2
            Calendar calendar = Calendar.getInstance();               
            SimpleDateFormat sdf = new SimpleDateFormat("MMM/dd/YYYY");
            calendar.set(Calendar.MONTH,Calendar.JUNE);
            calendar.set(Calendar.DAY_OF_MONTH,1);          
            int day = (Calendar.TUESDAY-calendar.get(Calendar.DAY_OF_WEEK));            
            if(day<0){
              calendar.add(Calendar.DATE,7+(day));
            }else{
                calendar.add(Calendar.DATE,day);
            }
            System.out.println("First date is "+sdf.format(calendar.getTime()));`enter code here`
Sujan
  • 15
  • 3
1

This will Give you First Saturday Of every month Of a Year of system date... u can also get other replace saturday with any other day

Invented By HK2 and Hemant

import java.util.Calendar;
import java.util.GregorianCalendar
           class Demo{
                 SimpleDateFormat format =new SimpleDateFormat("dd-MMM-yyyy");
                String DATE_FORMAT = "yyyy MM dd";

                SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
                Calendar c1 = Calendar.getInstance(); 

                String y=sdf.format(c1.getTime());
                String years=y.substring(0,4);
                int year=Integer.parseInt(years);

                Calendar cal = new GregorianCalendar(year, Calendar.JANUARY, 1);
                for (int i = 0, inc = 1; i <366 && cal.get(Calendar.YEAR) == year; i+=inc) {
                    if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) {

                        String frm="";
                        frm=format.format(cal.getTime());



                         // System.out.println("the value of the saturday is "+format.format(cal.getTime()));
                          cal.add(Calendar.MONTH,1);
                          cal.set(Calendar.DAY_OF_MONTH, 1);
                    } 

                    else {
                        cal.add(Calendar.DAY_OF_MONTH, 1);
                         }
                }
}
HK2
  • 17
  • 1
  • 5
1

Java.time

Using java.time library built into Java 8:

import java.time.{DayOfWeek, LocalDate}
import java.time.temporal.TemporalAdjusters.firstInMonth

val now = LocalDate.now() # 2015-11-23
val firstMonday = now.`with`(firstInMonth(DayOfWeek.MONDAY)) # 2015-11-02 (Monday)

You may choose any day from java.time.DayOfWeek.{MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY}.

If you need to add time information, you may use any available LocalDate to LocalDateTime conversion like

firstMonday.atStartOfDay() # 2015-11-02T00:00
Przemek
  • 7,111
  • 3
  • 43
  • 52
1

The simplest method of doing it with Java 8 is:

LocalDate firstSundayOfNextMonth = LocalDate
              .now()
              .with(firstDayOfNextMonth())
              .with(nextOrSame(DayOfWeek.MONDAY));
KayV
  • 12,987
  • 11
  • 98
  • 148
  • The OP is on Android. So similar code like in your answer can only be used if the OP is willing to import 3rd-party libraries like [Threeten-BP](https://github.com/ThreeTen/threetenbp) or my library [Time4A](http://time4j.net/javadoc-en/net/time4j/PlainDate.html#WEEKDAY_IN_MONTH). – Meno Hochschild Dec 06 '16 at 12:46
0

You can get the day of the week for a specific date in Java using Calendar class as discussed here:

How to determine day of week by passing specific date?

You can then loop over the dates in your range to find the first instance of Sunday and the second instance of Monday.

Community
  • 1
  • 1
Joe PP
  • 71
  • 2
  • 12
0
    Calendar calendar = Calendar.getInstance();
    calendar.set(year, month, date);
    int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);

So it'll give day for month first date. From this you can calculate what you want.

Manikandan
  • 3,025
  • 2
  • 19
  • 28
  • Why would you use SimpleDateFormat.parse() and a string to represent the date desired instead of using Calendar.set() for the year, month and date required? Surely representing what amounts to numerical data as a string in your code is opening yourself up to mistakes and bugs? – LeoR Jan 22 '14 at 15:32
  • You need to be careful when using Calendar.set (I know I suggested it, but it comes with caveats). The month is counted from 0, not 1. You can get round this confusion by using Calendar.JANUARY ... DECEMBER if it's static. – LeoR Jan 22 '14 at 17:05
0
public static Calendar getFirstMonday(Date startDate) {
    Calendar c = Calendar.getInstance();
    c.setTime(startDate);
    int day = c.get(Calendar.DAY_OF_WEEK);
    while (day != 1) {
        c.add(Calendar.DATE, 1);
        day = c.get(Calendar.DAY_OF_WEEK);
    }
    return c;
}

Find fisr monday of all weeks by:

            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

    String strDate = "01/01/2014";
    Date date;
    try {
        date = sdf.parse(strDate);

        for (int i = 0; i < 52; i++) {
            Calendar c = getFirstMonday(date);
            System.out.println("monday: " + sdf.format(c.getTime()));
            c.add(Calendar.DATE, 7);
        }
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
vipul mittal
  • 17,343
  • 3
  • 41
  • 44