Java Month Get getWeekOfMonth(String datetime)

Here you can find the source of getWeekOfMonth(String datetime)

Description

get Week Of Month

License

Open Source License

Declaration

public static int getWeekOfMonth(String datetime) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.text.ParseException;
import java.text.SimpleDateFormat;

import java.util.Calendar;
import java.util.Date;

public class Main {
    private static final SimpleDateFormat FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");

    public static int getWeekOfMonth(String datetime) {
        String start = datetime.substring(0, 8) + "01";
        Date day = parseDate(datetime);

        int i = 7;
        int w = 1;

        while (true) {
            if (day.getTime() < addDay(start, i).getTime()) {
                return w;
            }//from w ww  . j  ava  2s.com
            i = i + 7;
            w++;
        }
    }

    public static Date parseDate(String datetime) {
        try {
            return DATE_FORMAT.parse(datetime);
        } catch (ParseException e) {
            return new Date();
        }
    }

    public static Date addDay(String datetime, int day) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(parseDate(datetime));
        cal.add(Calendar.DAY_OF_YEAR, day);
        return cal.getTime();
    }

    public static Date parse(String datetime) {
        try {
            return FORMAT.parse(datetime);
        } catch (ParseException e) {
            return new Date();
        }
    }
}

Related

  1. getThisMonth()
  2. getThisMonthAndCycle()
  3. getThisMonthDate()
  4. getThisMonthLastDate()
  5. getTsOfMonth(Date date, boolean isEnd, boolean isPrevious)
  6. getWorkMonthLastDay(Date date)
  7. getYesterdayOnLastMonth(String yesterday)
  8. getYestMonth()