Example usage for java.util Calendar DAY_OF_WEEK

List of usage examples for java.util Calendar DAY_OF_WEEK

Introduction

In this page you can find the example usage for java.util Calendar DAY_OF_WEEK.

Prototype

int DAY_OF_WEEK

To view the source code for java.util Calendar DAY_OF_WEEK.

Click Source Link

Document

Field number for get and set indicating the day of the week.

Usage

From source file:it.sayservice.platform.smartplanner.cache.annotated.AnnotatedReader.java

public void buildTimetable(String router, String agencyId, boolean setTripsIds,
        List<AnnotatedTimetable> timetables) throws Exception {
    AgencyCacheIndex aci = new AgencyCacheIndex(agencyId);
    aci.setVersion(1);/*from  w  w w. ja  va2 s  .  c  o  m*/

    ObjectMapper mapper = new ObjectMapper();

    String cacheDir = System.getenv("OTP_HOME") + System.getProperty("file.separator") + router
            + System.getProperty("file.separator") + "cache" + System.getProperty("file.separator") + "client";
    String agencyDir = cacheDir + System.getProperty("file.separator") + agencyId;
    File dir = new File(agencyDir);
    if (!dir.exists()) {
        dir.mkdir();
    } else {
        for (File f : dir.listFiles()) {
            f.delete();
        }
    }

    Map<String, WeekdayFilter> weekdayFilter = handler.readAgencyWeekDay(router, agencyId);
    Map<String, WeekdayException> weekdayException = handler.readAgencyWeekDayExceptions(router, agencyId);

    Multimap<String, ExtendedAnnotatedColumn> extendedAnnotatedColumn = createExtendedAnnotatedColumns(
            timetables);
    SetMultimap<String, String> tripsSymbolicRouteId = TreeMultimap.create();

    List<SymbolicRouteDayInfoHashCalendar> agencySrdihs = Lists.newArrayList();

    for (String rId : extendedAnnotatedColumn.keySet()) {
        System.out.println("Generating " + rId);

        Map<String, AnnotatedColumn> tripsColumns = Maps.newTreeMap();
        Map<String, AnnotatedTimetable> tripsTable = Maps.newTreeMap();
        Map<String, AnnotatedTimetable> serviceTable = Maps.newTreeMap();

        AnnotatedTimetable baseTable = null;

        Multimap<String, String> daysTrips = ArrayListMultimap.create();
        SetMultimap<String, String> daysServices = TreeMultimap.create();
        Map<String, AnnotatedTimetable> daysTable = Maps.newTreeMap();
        Map<String, String> daysHashes = Maps.newTreeMap();
        Map<String, String> tripsRoutes = Maps.newTreeMap();

        for (ExtendedAnnotatedColumn ac : extendedAnnotatedColumn.get(rId)) {
            baseTable = ac.getSource();

            String tripId = agencyId + "_" + ac.getTripId();
            tripsSymbolicRouteId.put(tripId, rId);
            tripsRoutes.put(ac.getTripId(), ac.getRouteId());

            tripsColumns.put(tripId, ac);

            tripsTable.put(tripId, ac.getSource());

            String serviceId = agencyId + "_" + ac.getServiceId();

            serviceTable.put(serviceId, ac.getSource());

            WeekdayFilter filter = weekdayFilter.get(serviceId);
            if (filter == null) {
                System.out.println("ServiceId not found: " + serviceId);
            }

            Set<String> days = Sets.newHashSet();

            DateFormat df = new SimpleDateFormat("yyyyMMdd");
            String from = filter.getFromDate();
            String to = filter.getToDate();

            Calendar fromDate = new GregorianCalendar();
            Calendar toDate = new GregorianCalendar();

            fromDate.setTime(df.parse(from));
            toDate.setTime(df.parse(to));
            Calendar date = new GregorianCalendar();
            date.setTime(fromDate.getTime());
            String prevDay = null;

            while (df.format(date.getTime()).compareTo(to) <= 0) {
                String day = df.format(date.getTime());

                boolean sameDay = day.equals(prevDay);

                if (!sameDay) {
                    int dotw = convertDayOfTheWeek(date.get(Calendar.DAY_OF_WEEK));
                    if (filter.getDays()[dotw]) {
                        days.add(day);
                    }
                }
                prevDay = day;
                date.setTime(new Date(date.getTime().getTime()));
                date.add(Calendar.DAY_OF_YEAR, 1);
            }

            WeekdayException ex = weekdayException.get(serviceId);
            if (ex != null) {
                for (String toAdd : ex.getAdded()) {
                    days.add(toAdd);
                }
                for (String toRemove : ex.getRemoved()) {
                    days.remove(toRemove);
                }
            }

            ac.setDays(Lists.newArrayList(days));

            for (String day : days) {
                daysTable.put(day, baseTable);
                daysTrips.put(day, tripId);
                daysServices.put(day, serviceId);
            }

        }

        Map<String, CacheTable> hashTable = Maps.newTreeMap();

        SymbolicRouteDayInfoHashCalendar srdihs = new SymbolicRouteDayInfoHashCalendar();
        srdihs.setAgencyId(agencyId);
        agencySrdihs.add(srdihs);

        Map<String, String> srdihsCalendar = Maps.newTreeMap();
        Map<String, SymbolicRouteDayInfo> srdihsValues = Maps.newTreeMap();
        srdihs.setCalendar(srdihsCalendar);
        srdihs.setValues(srdihsValues);
        srdihs.setRouteId(rId);

        for (String day : daysTrips.keySet()) {
            List<String> dayTrips = Lists.newArrayList(daysTrips.get(day));
            List<String> dayServices = Lists.newArrayList(daysServices.get(day));
            String hash = getEqString(dayServices, agencyId);

            if (daysHashes.containsKey(day)) {
                continue;
            }

            daysHashes.put(day, hash);
            Set<String> dayServicesSet = daysServices.get(day);

            AnnotatedTimetable reducedTable = reduceAnnotatedTimetable(daysTable.get(day), dayServicesSet,
                    agencyId);

            CacheTable ct = new CacheTable();

            List<String> tripIds = Lists.newArrayList();
            List<List<String>> compressedTimes = Lists.newArrayList();
            ct.setTimes(compressedTimes);

            for (String trip : dayTrips) {
                int index = trip.indexOf("_");
                tripIds.add(trip.substring(index + 1));
                compressedTimes.add(tripsColumns.get(trip).getTimes());
            }

            if (setTripsIds) {
                ct.setTripIds(tripIds);
            }

            List<String> routesIds = Lists.newArrayList();
            for (String ti : tripIds) {
                routesIds.add(tripsRoutes.get(ti));
            }

            ct.setStops(reducedTable.getStopNames());
            ct.setStopsId(reducedTable.getStopIds());
            ct.setInvisibles(reducedTable.getInvisibles());
            ct.setFrequency(reducedTable.getFrequency());
            ct.setLine(reducedTable.getLine());
            ct.setRoutesIds(routesIds);

            ct.setShortDescription(reducedTable.getShortDescription());
            ct.setLongDescription(reducedTable.getLongDescription());
            ct.setValidity(reducedTable.getValidity());
            ct.setSchedule(reducedTable.getSchedule());

            ct.compress();

            hashTable.put(hash, ct);

            if (!srdihsValues.containsKey(hash)) {
                SymbolicRouteDayInfo srdi = new SymbolicRouteDayInfo(reducedTable);
                StopNames sn = new StopNames();
                sn.setRouteId(rId);
                sn.setIds(reducedTable.getStopIds());
                sn.setNames(reducedTable.getStopNames());
                srdi.setStopNames(sn);
                srdi.setTripIds(tripIds);
                srdihsValues.put(hash, srdi);
            }
            srdihsCalendar.put(day, hash);
        }

        System.out.println("Writing " + rId);

        String calendar = agencyDir + System.getProperty("file.separator") + "calendar_" + rId + ".js";
        mapper.writeValue(new File(calendar), daysHashes);
        for (String hash : hashTable.keySet()) {
            String hashFile = agencyDir + System.getProperty("file.separator") + rId + "_" + hash + ".js";
            mapper.writeValue(new File(hashFile), hashTable.get(hash));

            CacheIndexEntry cie = new CacheIndexEntry();
            cie.setId(rId + "_" + hash);
            cie.setVersion(1);
            cie.setStatus(CacheEntryStatus.ADDED);
            aci.getEntries().put(rId + "_" + hash, cie);
        }

    }

    String indexFile = cacheDir + System.getProperty("file.separator") + agencyId + "_index.txt";
    File aciFile = new File(indexFile);
    if (aciFile.exists()) {
        AgencyCacheIndex oldAci = mapper.readValue(aciFile, AgencyCacheIndex.class);
        aci.setVersion(oldAci.getVersion() + 1);
    }
    mapper.writeValue(new File(indexFile), aci);

    String auxDir = cacheDir + System.getProperty("file.separator") + Constants.AUXILIARY_CACHE_DIR;
    String infoFile = auxDir + System.getProperty("file.separator") + agencyId + "_info.txt";
    mapper.writeValue(new File(infoFile), agencySrdihs);

    String symbolicFile = auxDir + System.getProperty("file.separator") + agencyId + "_symbolic_trips.txt";

    Map<String, Collection<String>> map = Maps.newTreeMap();
    for (String key : tripsSymbolicRouteId.keys()) {
        List<String> rids = Lists.newArrayList();
        rids.addAll(tripsSymbolicRouteId.get(key));
        map.put(key, rids);
    }

    mapper.writeValue(new File(symbolicFile), map);
}

From source file:jp.co.ctc_g.jfw.core.util.Dates.java

/**
 * ???.//from  w  w w . j a v a2  s. c o  m
 * @return ???java.util.Calendar?
 */
public static int getDayOfWeek() {

    Calendar currentCalendar = Dates.getCalendarInstance();
    return currentCalendar.get(Calendar.DAY_OF_WEEK);
}

From source file:com.seajas.search.attender.service.attender.dao.ProfileDAO.java

/**
 * Find all notifiable subscribers from the given profile.
 * /*from w  w  w  .  ja v  a 2 s. c  o  m*/
 * @param calendar
 * @param profile
 * @return List<ProfileSubscriber>
 */
public List<ProfileSubscriber> findNotifiableSubscribers(final Calendar calendar,
        final List<ProfileSubscriber> subscribers) {
    if (!calendar.getTimeZone().getID().equals("UTC"))
        throw new IllegalArgumentException(
                "The given calendar must have a UTC timezone (has " + calendar.getTimeZone().getID() + ")");

    // Calculate the current time in UTC

    Integer currentHour = calendar.get(Calendar.HOUR_OF_DAY), currentMinute = calendar.get(Calendar.MINUTE),
            currentDay = calendar.get(Calendar.DAY_OF_WEEK);
    Date currentTime = new Date(calendar.getTimeInMillis());

    // Return a list of all applicable subscribers for this profile

    List<ProfileSubscriber> result = new ArrayList<ProfileSubscriber>();

    // Find all active profiles' confirmed subscribers whose notification preference fall within the current day and whose time
    // values are greater than or equal to the current hour / minute; then take 7 days for weekly updates, 1 for daily updates,
    // and 1 for weekdays where Saturday / Sunday are excluded

    for (ProfileSubscriber subscriber : subscribers) {
        Integer subscriberDay = subscriber.getNotificationDay(),
                subscriberHour = subscriber.getNotificationHour(),
                subscriberMinute = subscriber.getNotificationMinute();
        Date lastNotification = subscriber.getLastNotification();
        NotificationType subscriberType = subscriber.getNotificationType();

        // Correct for the user-specific timezone

        TimeZone timeZone = TimeZone.getTimeZone(subscriber.getTimeZone());

        // Take leap seconds into account, although we're not so precise to really care

        if (subscriberMinute != null) {
            subscriberMinute -= (int) ((timeZone.getOffset(calendar.getTimeInMillis()) % MILLISECONDS_PER_HOUR)
                    / MILLISECONDS_PER_MINUTE);

            if (subscriberMinute < 0) {
                subscriberMinute += 60;
                subscriberHour--;
            } else if (subscriberMinute > 59) {
                subscriberMinute -= 60;
                subscriberHour++;
            }
        }

        if (subscriberHour != null) {
            subscriberHour -= (int) (timeZone.getOffset(calendar.getTimeInMillis()) / MILLISECONDS_PER_HOUR);

            if (subscriberHour < 0) {
                subscriberHour += 24;

                if (subscriberDay != null)
                    subscriberDay--;
            } else if (subscriberHour > 23) {
                subscriberHour -= 24;

                if (subscriberDay != null)
                    subscriberDay++;
            }
        }

        if (subscriberDay == -1)
            subscriberDay = 6;
        else if (subscriberDay == 7)
            subscriberDay = 0;

        // Now determine the actual applicability (last_notification is stored as a UTC date, so does not need to be converted)

        if (subscriber.getIsConfirmed() && ((subscriberType.equals(NotificationType.Weekly)
                && subscriberDay.equals(currentDay) && subscriberHour <= currentHour
                && subscriberMinute <= currentMinute && dateDifference(lastNotification, currentTime) >= 6)
                || (subscriberType.equals(NotificationType.Weekdays) && currentDay != Calendar.SATURDAY
                        && currentDay != Calendar.SUNDAY && subscriberHour <= currentHour
                        && subscriberMinute <= currentMinute
                        && !DateUtils.isSameDay(lastNotification, currentTime))
                || (subscriberType.equals(NotificationType.Daily) && subscriberHour <= currentHour
                        && subscriberMinute <= currentMinute
                        && !DateUtils.isSameDay(lastNotification, currentTime)))) {
            if (logger.isInfoEnabled())
                logger.info("Adding subscriber '" + subscriber.getUniqueId() + "' with e-mail '"
                        + subscriber.getEmail() + "' to be notified");

            result.add(subscriber);
        } else if (logger.isDebugEnabled()) {
            if (!subscriber.getIsConfirmed())
                logger.debug("Not adding subscriber '" + subscriber.getUniqueId() + "' with e-mail '"
                        + subscriber.getEmail() + "' - not confirmed");
            else if (subscriberType.equals(NotificationType.Direct))
                logger.debug("Not adding subscriber '" + subscriber.getUniqueId() + "' with e-mail '"
                        + subscriber.getEmail()
                        + "' - direct notifications are handled by search-enricher instances");
            else if (subscriberType.equals(NotificationType.Weekly)) {
                if (!subscriberDay.equals(currentDay))
                    logger.debug("Not adding subscriber '" + subscriber.getUniqueId() + "' with e-mail '"
                            + subscriber.getEmail() + "' - weekly notification does not fall on current day");
                if (!(subscriberHour <= currentHour && subscriberMinute <= currentMinute))
                    logger.debug("Not adding subscriber '" + subscriber.getUniqueId() + "' with e-mail '"
                            + subscriber.getEmail() + "' - weekly notification falls outside of current time");
                if (!(dateDifference(lastNotification, currentTime) >= 6))
                    logger.debug("Not adding subscriber '" + subscriber.getUniqueId() + "' with e-mail '"
                            + subscriber.getEmail()
                            + "' - weekly notification difference (in days) smaller than 7");
            } else if (subscriberType.equals(NotificationType.Weekdays)) {
                if (!(currentDay != Calendar.SATURDAY && currentDay != Calendar.SUNDAY))
                    logger.debug("Not adding subscriber '" + subscriber.getUniqueId() + "' with e-mail '"
                            + subscriber.getEmail() + "' - weekday notification does not fall on weekday");
                if (!(subscriberHour <= currentHour && subscriberMinute <= currentMinute))
                    logger.debug("Not adding subscriber '" + subscriber.getUniqueId() + "' with e-mail '"
                            + subscriber.getEmail() + "' - weekday notification falls outside of current time");
                if (DateUtils.isSameDay(lastNotification, currentTime))
                    logger.debug("Not adding subscriber '" + subscriber.getUniqueId() + "' with e-mail '"
                            + subscriber.getEmail()
                            + "' - weekday notification difference indicates a notification has already gone out today");
            } else if (subscriberType.equals(NotificationType.Daily)) {
                if (!(subscriberHour <= currentHour && subscriberMinute <= currentMinute))
                    logger.debug("Not adding subscriber '" + subscriber.getUniqueId() + "' with e-mail '"
                            + subscriber.getEmail() + "' - daily notification falls outside of current time");
                if (DateUtils.isSameDay(lastNotification, currentTime))
                    logger.debug("Not adding subscriber '" + subscriber.getUniqueId() + "' with e-mail '"
                            + subscriber.getEmail()
                            + "' - daily notification difference indicates a notification has already gone out today");
            }
        }
    }

    return result;
}

From source file:com.clustercontrol.calendar.composite.CalendarMonthComposite.java

@Override
public void update() {
    if (m_calendarId == null || m_summaryInfo == null) {
        return;// w w  w  . j  a  v a2 s.  co  m
    }

    yearMonth.setText(String.format("%04d/%02d", nowYear, nowMonth));
    //?
    /**  */
    Calendar calendar = null;
    calendar = Calendar.getInstance(TimezoneUtil.getTimeZone());
    calendar.clear();
    calendar.set(nowYear, nowMonth - 1, 1);
    //??????????
    /** ????? */
    int startDate = calendar.get(Calendar.DAY_OF_WEEK);
    /** ???? */
    int lastDate = (m_summaryInfo.size() + 1);

    /***************************************************
     * 
     *           j=0  j=1  j=2  j=3  j=4  j=5  j=6
     *       | Sun| Mon| Thu| Wed| Thu| Fri| Sat|
     *       ------------------------------------
     *   i=1                               | 1  |
     *   i=2 | 2  | 3  | 4  | 5  | 6  | 7  | 8  |
     *   i=3 | 9  | 10 | 11 | 12 | 13 | 14 | 15 |
     *   i=4 | 16 | 17 | 18 | 19 | 20 | 21 | 22 |
     *   i=5 | 23 | 24 | 25 | 26 | 27 | 28 | 29 |
     *   i=6 | 30 | 31 |
     *
     ***************************************************/
    calTable.removeAll();
    //??
    int day = 1;

    //??
    for (int i = 0; i < 6; i++) { // 6(1????6?)
        //???????????
        int j = startDate;
        //?2????
        startDate = GetCalendarMonthTableDefine.SUNDAY;

        //??
        String[] days = new String[8];
        //1????
        TableItem weekTableItem = new TableItem(calTable, SWT.NONE);
        WidgetTestUtil.setTestId(this, null, weekTableItem);
        //weekTableItem.setData(ClusterControlPlugin.CUSTOM_WIDGET_ID, "calendarMonthCompositeWeekTableItem");

        //??????
        while (j < days.length && day < lastDate) {
            //???
            String sign = "";
            boolean selectedFlag = false;
            if (selectedDay <= day && day < selectedDay + 7) {
                selectedFlag = true;
            }
            switch (m_summaryInfo.get(day - 1)) {
            case 0:
                //
                sign = Messages.getString("view.calendar.month.all");
                weekTableItem.setBackground(j, ColorConstantsWrapper.green());
                break;
            case 1:
                //
                sign = Messages.getString("view.calendar.month.part");
                weekTableItem.setBackground(j, ColorConstantsWrapper.yellow());
                break;
            case 2:
                //
                sign = Messages.getString("view.calendar.month.none");
                weekTableItem.setBackground(j, ColorConstantsWrapper.red());
                break;
            default: // ???
                break;
            }
            if (selectedFlag) {
                weekTableItem.setFont(j, boldFont);
            } else {
                weekTableItem.setFont(j, normalFont);
            }
            weekTableItem.setForeground(j, ColorConstantsWrapper.black());
            //?????
            days[j] = String.format("%02d", day) + sign;
            j++;
            day++;

            WidgetTestUtil.setTestId(this, "weektableitem" + j, weekTableItem);
        }
        weekTableItem.setText(days);
    }
}

From source file:se.technipelago.weather.chart.Generator.java

public Map<String, Object> getWeatherData() {
    Map<String, Object> map = new HashMap<String, Object>();

    // Put archived data into the map.
    setArchivedData(map);/*from w ww .j  a  v  a 2  s.c  om*/

    // Put current data into the map.
    setCurrentData(map);

    // Daily high/low values.
    //
    Calendar cal = Calendar.getInstance();
    cal.setTime((Date) map.get("timestamp"));
    cal.set(Calendar.HOUR_OF_DAY, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);
    cal.add(Calendar.DAY_OF_MONTH, -6);
    Date day7 = cal.getTime();
    cal.add(Calendar.DAY_OF_MONTH, 6);
    Date day0 = cal.getTime();
    cal.add(Calendar.DAY_OF_MONTH, 1);
    cal.add(Calendar.MILLISECOND, -1);
    Date day1 = cal.getTime();
    // High values.
    setHiLowData(day0, day1, "temp_out", true, map, "dailyHighTemp");
    setHiLowData(day0, day1, "hum_out", true, map, "dailyHighHumidity");
    setHiLowData(day0, day1, "wind_high", true, map, "dailyHighWind");
    // Low values.
    setHiLowData(day0, day1, "temp_out", false, map, "dailyLowTemp");
    setHiLowData(day0, day1, "hum_out", false, map, "dailyLowHumidity");
    setHiLowData(day0, day1, "wind_avg", false, map, "dailyLowWind");

    map.put("rain_today", getValue(day0, day1, "rain", SUM));

    map.put("solar_hours", getSolarHours(new Timespan(day7, day1)));

    cal.set(Calendar.MONTH, Calendar.JUNE);
    cal.set(Calendar.DAY_OF_MONTH, 19);
    cal.set(Calendar.HOUR_OF_DAY, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);
    Date midsummer = cal.getTime();
    cal.setTime(new Date());
    cal.set(Calendar.HOUR_OF_DAY, 23);
    cal.set(Calendar.MINUTE, 59);
    cal.set(Calendar.SECOND, 59);
    cal.set(Calendar.MILLISECOND, 999);
    while (cal.get(Calendar.DAY_OF_WEEK) != Calendar.THURSDAY) {
        cal.add(Calendar.DAY_OF_MONTH, -1);
    }
    Date thursday = cal.getTime();
    if (thursday.getTime() > midsummer.getTime()) {
        map.put("solligan", getSolarHours(new Timespan(midsummer, thursday)));
        map.put("solligan_time", thursday);
    } else {
        map.put("solligan", Float.valueOf(0));
    }

    return map;
}

From source file:Holidays.java

public static java.util.Calendar MemorialDayObserved(int nYear) {
    // Last Monday in May
    int nX;// w  ww  . ja  v a2  s  .  co m
    int nMonth = 4; //May
    java.util.Calendar cal = java.util.Calendar.getInstance();
    cal.set(nYear, nMonth, 31);

    nX = cal.get(Calendar.DAY_OF_WEEK);

    switch (nX) {
    case 0: // Sunday
        cal = java.util.Calendar.getInstance();
        cal.set(nYear, nMonth, 25);
        return cal;
    case 1: // Monday
        cal = java.util.Calendar.getInstance();
        cal.set(nYear, nMonth, 31);
        return cal;
    case 2: // Tuesday
        cal = java.util.Calendar.getInstance();
        cal.set(nYear, nMonth, 30);
        return cal;
    case 3: // Wednesday
        cal = java.util.Calendar.getInstance();
        cal.set(nYear, nMonth, 29);
        return cal;
    case 4: // Thrusday
        cal = java.util.Calendar.getInstance();
        cal.set(nYear, nMonth, 28);
        return cal;
    case 5: // Friday
        cal = java.util.Calendar.getInstance();
        cal.set(nYear, nMonth, 27);
        return cal;
    default: // Saturday
        cal = java.util.Calendar.getInstance();
        cal.set(nYear, nMonth, 26);
        return cal;

    }
}

From source file:com.oasis.wolfburg.service.truckRSSchedule.TruckRSJobComponent.java

private void setDateSpan(TruckRSJobSO so) {
    Date start = new Date();
    Date end = new Date();
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.DAY_OF_MONTH, -(Calendar.DAY_OF_WEEK + 6));
    start = cal.getTime();//w w w. ja va 2 s . c  o  m
    cal.setTime(start);
    /**
     * ???+42
     */
    cal.add(Calendar.DAY_OF_MONTH, 41);
    end = cal.getTime();
    so.setStartDate(start);
    so.setEndDate(end);
}

From source file:com.px100systems.util.SpringELCtx.java

/**
 * Period start/*from   w  w w .j a  v a 2  s.  co  m*/
 * @param date time
 * @param arg d/w/M/y
 * @return adjusted time
 */
public static Date periodStart(Date date, String arg) {
    if (date == null)
        return null;

    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    cal.set(Calendar.HOUR_OF_DAY, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);

    if (arg.endsWith("d"))
        return cal.getTime();
    else if (arg.endsWith("M")) {
        cal.set(Calendar.DAY_OF_MONTH, 1);
        return cal.getTime();
    } else if (arg.endsWith("y")) {
        cal.set(Calendar.DAY_OF_YEAR, 1);
        return cal.getTime();
    } else if (arg.endsWith("w")) {
        cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
        return cal.getTime();
    }

    return date;
}

From source file:com.frey.repo.DateUtil.java

/*****************************************
 * @return interger//from w ww .ja  v  a  2  s . co m
 * @ ??
 ****************************************/
public static String getYearWeekFirstDay(int yearNum, int weekNum) throws ParseException {

    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.YEAR, yearNum);
    cal.set(Calendar.WEEK_OF_YEAR, weekNum);
    cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
    // ????
    String tempYear = Integer.toString(yearNum);
    String tempMonth = Integer.toString(cal.get(Calendar.MONTH) + 1);
    String tempDay = Integer.toString(cal.get(Calendar.DATE));
    String tempDate = tempYear + "-" + tempMonth + "-" + tempDay;
    return setDateFormat(tempDate, "yyyy-MM-dd");

}

From source file:com.haulmont.timesheets.gui.weeklytimesheets.SimpleWeeklyTimesheets.java

protected void initDaysColumns() {
    for (Date current = firstDayOfWeek; current.getTime() <= lastDayOfWeek.getTime(); current = DateUtils
            .addDays(current, 1)) {/* w ww .jav a 2s.  c om*/
        final DayOfWeek day = DayOfWeek
                .fromCalendarDay(DateUtils.toCalendar(current).get(Calendar.DAY_OF_WEEK));
        final String columnId = day.getId() + COLUMN_SUFFIX;
        weeklyTsTable.addGeneratedColumn(columnId, new Table.ColumnGenerator<WeeklyReportEntry>() {
            @Override
            public Component generateCell(final WeeklyReportEntry entity) {
                List<TimeEntry> timeEntries = entity.getDayOfWeekTimeEntries(day);
                if (CollectionUtils.isEmpty(timeEntries)
                        || timeEntries.size() == 1 && PersistenceHelper.isNew(timeEntries.get(0))) {
                    return createTextFieldForTimeInput(entity);
                } else {
                    return createLinkAndActionsForExistingEntry(entity, timeEntries);
                }
            }

            private Component createLinkAndActionsForExistingEntry(WeeklyReportEntry reportEntry,
                    List<TimeEntry> timeEntries) {
                HBoxLayout hBox = componentsFactory.createComponent(HBoxLayout.class);
                hBox.setSpacing(true);

                if (timeEntries.size() == 1) {
                    createLinkToSingleTimeEntry(reportEntry, timeEntries, hBox);
                } else {
                    createLinkToMultipleTimeEntries(reportEntry, hBox, timeEntries.get(0).getDate());
                }
                createRemoveButton(reportEntry, hBox);

                return hBox;
            }

            private void createRemoveButton(final WeeklyReportEntry reportEntry, HBoxLayout hBox) {
                LinkButton removeButton = componentsFactory.createComponent(LinkButton.class);
                removeButton.setIcon("icons/remove.png");
                removeButton.setAlignment(Alignment.MIDDLE_RIGHT);
                removeButton.setAction(new ComponentsHelper.CustomRemoveAction("timeEntryRemove", getFrame()) {
                    @Override
                    protected void doRemove() {
                        removeTimeEntries(reportEntry.getDayOfWeekTimeEntries(day));
                        reportEntry.changeDayOfWeekTimeEntries(day, null);
                        weeklyTsTable.repaint();
                    }
                });
                hBox.add(removeButton);
            }

            private void createLinkToMultipleTimeEntries(final WeeklyReportEntry reportEntry, HBoxLayout hBox,
                    final Date date) {
                final LinkButton linkButton = componentsFactory.createComponent(LinkButton.class);
                linkButton.setCaption(reportEntry.getTotalForDay(day).toString());
                linkButton.setAction(new AbstractAction("edit") {

                    @Override
                    public void actionPerform(Component component) {
                        Window window = openWindow("ts$TimeEntry.lookup", WindowManager.OpenType.DIALOG,
                                ParamsMap.of("date", date, "task", reportEntry.getTask(), "activityType",
                                        reportEntry.getActivityType(), "user",
                                        userSession.getCurrentOrSubstitutedUser()));
                        window.addCloseListener(actionId -> updateWeek());
                    }
                });
                hBox.add(linkButton);
            }

            private void createLinkToSingleTimeEntry(final WeeklyReportEntry reportEntry,
                    List<TimeEntry> timeEntries, HBoxLayout hBox) {
                final TimeEntry timeEntry = timeEntries.get(0);
                final LinkButton linkButton = componentsFactory.createComponent(LinkButton.class);
                linkButton.setCaption(reportEntry.getTotalForDay(day).toString());
                linkButton.setAction(new AbstractAction("edit") {
                    @Override
                    public void actionPerform(Component component) {
                        openTimeEntryEditor(timeEntry);
                    }
                });

                hBox.add(linkButton);
            }

            private Component createTextFieldForTimeInput(WeeklyReportEntry reportEntry) {
                TextField timeField = componentsFactory.createComponent(TextField.class);
                timeField.setWidth("100%");
                timeField.setHeight("22px");
                timeField.setDatasource(weeklyTsTable.getItemDatasource(reportEntry), day.getId() + "Time");
                return timeField;
            }
        });
        weeklyTsTable.setColumnWidth(columnId, 80);

        Table.Column column = weeklyTsTable.getColumn(columnId);
        column.setAggregation(ComponentsHelper.createAggregationInfo(
                projectsService.getEntityMetaPropertyPath(WeeklyReportEntry.class, day.getId()),
                new WeeklyReportEntryAggregation()));
    }
}