Example usage for java.util Calendar DAY_OF_MONTH

List of usage examples for java.util Calendar DAY_OF_MONTH

Introduction

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

Prototype

int DAY_OF_MONTH

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

Click Source Link

Document

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

Usage

From source file:com.pureinfo.tgirls.servlet.WelcomeMsgUtils.java

public static RandomEvent doGetWelcomEvent(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    logger.debug("to get welcome event.");

    User loginUser = CookieUtils.getLoginUser(request, response);
    if (loginUser == null) {
        return null;
    }/*from w w w  .java  2s  .c  o  m*/

    IUserMgr usermgr = null;//(IUserMgr) ArkContentHelper.getContentMgrOf(User.class);
    try {
        usermgr = (IUserMgr) ArkContentHelper.getContentMgrOf(User.class);
        if (loginUser.getLastLoginTime() == null) {
            loginUser.setLastLoginTime(new Date());
            usermgr.save(loginUser);
        }
    } catch (Exception e1) {
        logger.error(e1);
        return null;
    }

    if (DateUtils.isSameDay(loginUser.getLastLoginTime(), new Date())) {
        return null;
    } else {
        //????
        createNormalRandomEvent(loginUser);
    }

    Calendar now = Calendar.getInstance();
    int m = now.get(Calendar.MONTH);
    int d = now.get(Calendar.DAY_OF_MONTH);

    List<RandomEvent> todayEvents = (List<RandomEvent>) cache.get(WELCOME_EVENT_KEY + "." + m + "." + d);
    if (todayEvents == null) {
        todayEvents = new ArrayList<RandomEvent>();

        logger.debug("today events is empty. reload.");

        List<RandomEvent> allWelcomeRandomEvents = null;
        try {
            allWelcomeRandomEvents = getWelcomeEvents();
        } catch (PureException e) {
            logger.error("error when get welcome events.", e);
        }

        if (allWelcomeRandomEvents == null || allWelcomeRandomEvents.isEmpty()) {

            logger.debug("all welcome events is empty.");

            return null;
        }

        List<RandomEvent> normalEvents = new ArrayList<RandomEvent>();// 

        Calendar c1 = Calendar.getInstance();// Calendar.getInstance();
        Calendar today = Calendar.getInstance();
        for (Iterator<RandomEvent> iterator = allWelcomeRandomEvents.iterator(); iterator.hasNext();) {
            RandomEvent randomEvent = iterator.next();
            String month_day = randomEvent.getEventMonthDay();
            if (StringUtils.isNotEmpty(month_day)) {
                try {
                    int i = month_day.indexOf("-");
                    int month = NumberUtils.toInt(month_day.substring(0, i), -1);
                    int day = NumberUtils.toInt(month_day.substring(i + 1), -1);
                    c1.clear();
                    c1 = Calendar.getInstance();

                    //                        logger.debug("the random event [" + randomEvent.getEventInfo() + "]  month:" + month
                    //                                + " ,day: " + day);

                    if (month != -1) {
                        c1.set(Calendar.MONTH, month - 1);
                    }
                    if (day != -1) {
                        c1.set(Calendar.DAY_OF_MONTH, day);
                    }

                    if (DateUtils.isSameDay(c1, today)) {
                        todayEvents.add(randomEvent);
                    }
                } catch (Exception e) {
                }
            } else {
                normalEvents.add(randomEvent);
            }
        }

        if (todayEvents == null || todayEvents.isEmpty()) {
            if (normalEvents.isEmpty()) {

                logger.debug("today events is empty, and normal events is empty too.");

                return null;
            } else {
                todayEvents.addAll(normalEvents);
            }
        }

        Collections.sort(todayEvents, new BeanComparator("eventScale"));
        todayTotalScale = 0;
        for (Iterator<RandomEvent> iterator = todayEvents.iterator(); iterator.hasNext();) {
            RandomEvent randomEvent2 = iterator.next();
            todayTotalScale += randomEvent2.getEventScale();
        }
        cache.put(WELCOME_EVENT_KEY + "." + m + "." + d, todayEvents);

    }

    if (todayEvents == null || todayEvents.isEmpty()) {
        logger.debug("today events is empty, system events is empty .");

        return null;
    }

    int random = new Random().nextInt(todayTotalScale);
    RandomEvent todayEvent = null;
    int start = 0;
    int end = 0;
    for (int i = 0; i < todayEvents.size(); i++) {
        if (i == 0) {
            start = 0;
            end = todayEvents.get(i).getEventScale();
        } else {
            start = end;
            end = end + todayEvents.get(i).getEventScale();
        }

        if (random >= start && random < end) {
            todayEvent = todayEvents.get(i);
            break;
        }
    }
    if (todayEvent == null) {
        return null;
    }

    try {
        logger.info("welcome event[" + todayEvent.getEventInfo() + "]");

        loginUser.setFunds(loginUser.getFunds() + todayEvent.getEventMoney());
        loginUser.setAssets(loginUser.getAssets() + todayEvent.getEventMoney());
        loginUser.setLastLoginTime(new Date());

        usermgr.save(loginUser);

        //ScriptWriteUtils.reBuildUserInfoScript(loginUser);

    } catch (Exception e) {
        logger.error(e);
        return null;
    }

    return todayEvent;
}

From source file:com.hemou.android.util.StrUtils.java

/**
 * {@link https://en.wikipedia.org/wiki/List_of_time_zones_by_country}
 * @param time//from w w w  . ja v  a 2 s . c om
 * @return
 */
public static String convertTimeWithTimeZome(long time) {

    Calendar cal = Calendar.getInstance();
    cal.setTimeZone(TimeZone.getTimeZone("UTC"));
    cal.setTimeInMillis(time);
    return (cal.get(Calendar.YEAR) + " " + (cal.get(Calendar.MONTH) + 1) + " " + cal.get(Calendar.DAY_OF_MONTH)
            + " " + cal.get(Calendar.HOUR_OF_DAY) + ":" + cal.get(Calendar.MINUTE));

}

From source file:XSDDateTime.java

public static String getDateTime(Calendar cal) {
    if (!cal.getTimeZone().equals(TimeZone.getTimeZone("GMT+00:00"))) {
        throw new InvalidParameterException();
    }// w w w  .  j a  v a  2 s  .  co m
    int year = cal.get(Calendar.YEAR);
    int month = cal.get(Calendar.MONTH);
    month++;
    String monthString = pad(month);
    int day = cal.get(Calendar.DAY_OF_MONTH);
    String dayString = pad(day);
    int hour = cal.get(Calendar.HOUR_OF_DAY);
    String hourString = pad(hour);
    int minutes = cal.get(Calendar.MINUTE);
    String minutesString = pad(minutes);
    int seconds = cal.get(Calendar.SECOND);
    String secondsString = pad(seconds);

    return year + "-" + monthString + "-" + dayString + "T" + hourString + ":" + minutesString + ":"
            + secondsString + "Z";
}

From source file:com.imos.sample.pi.PythonTemperatureSensor.java

public void pythonTemperatureSensor() {

    try {/*w ww .j a v  a 2 s .  c  o m*/
        String cmd = "sudo python /home/pi/Adafruit_Python_DHT/examples/AdafruitDHT.py 22 4";
        int count = 0;
        JSONArray array = new JSONArray();
        int dayOfMonth = 0;
        cal.setTime(new Date());
        dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
        while (true) {
            Process p = Runtime.getRuntime().exec(cmd);
            p.waitFor();

            StringBuilder output = new StringBuilder();
            BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line = "";
            while ((line = reader.readLine()) != null) {
                output.append(line);
            }
            String result = output.toString(), tempStr;
            double temp, humid;
            if (result != null && !result.trim().isEmpty()) {
                tempStr = result.substring(result.indexOf("Humid"));
                result = result.substring(result.indexOf("=") + 1, result.indexOf("C") - 1);
                temp = Double.parseDouble(result);
                result = tempStr;
                result = result.substring(result.indexOf("=") + 1, result.indexOf("%"));
                humid = Double.parseDouble(result);

                JSONObject data = new JSONObject();
                data.put("temp", temp);
                data.put("humid", humid);
                data.put("time", new Date().getTime());

                array.put(data);
            }

            Thread.sleep(60000);
            count++;
            if (count == 60) {
                cal.setTime(new Date());
                StringBuilder builder = new StringBuilder();
                builder.append(cal.get(Calendar.DAY_OF_MONTH));
                builder.append("-");
                builder.append(cal.get(Calendar.MONTH));
                builder.append("-");
                builder.append(cal.get(Calendar.YEAR));
                builder.append("-");
                builder.append(cal.get(Calendar.HOUR_OF_DAY));
                builder.append("_");
                builder.append(cal.get(Calendar.MINUTE));
                String name = builder.toString();
                Logger.getLogger(PiMainFile.class.getName()).log(Level.INFO, "{0} recorded", name);
                try (BufferedWriter writer = new BufferedWriter(new FileWriter(name + "_data.json"))) {
                    writer.append(array.toString());
                } catch (IOException ex) {

                }
                System.out.println(builder.toString());
                count = 0;
                array = new JSONArray();
                if (dayOfMonth != cal.get(Calendar.DAY_OF_MONTH)) {
                    builder = new StringBuilder();
                    builder.append(cal.get(Calendar.DAY_OF_MONTH));
                    builder.append("-");
                    builder.append(cal.get(Calendar.MONTH));
                    builder.append("-");
                    builder.append(cal.get(Calendar.YEAR));
                    String dirName = builder.toString();
                    File newDir = new File("./" + dirName);
                    newDir.mkdir();

                    File files = new File("./");
                    for (File file : files.listFiles()) {
                        if (file.getName().endsWith(".json")) {
                            file.renameTo(new File("./" + dirName + File.separator + file.getName()));
                        }
                    }

                    dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
                }
            }
        }
    } catch (IOException | InterruptedException ex) {
        Logger.getLogger(PythonTemperatureSensor.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.ccoe.build.tracking.BatchUpdateDurationJob.java

public void execute(JobExecutionContext context) {
    System.out.println("[INFO] " + new Date() + " Start executing BatchUpdateDurationJob...");
    long startRunningTime = System.currentTimeMillis();

    Calendar startDate = Calendar.getInstance();
    startDate.add(Calendar.DAY_OF_MONTH, -5);

    Calendar endDate = Calendar.getInstance();
    endDate.add(Calendar.DAY_OF_MONTH, 1);

    String startDateString = dateFormatter.format(startDate.getTime());
    String endDateString = dateFormatter.format(endDate.getTime());

    System.out.println("Date Range: " + startDateString + "   ~   " + endDateString);

    System.out.println("===== Batch updating build duration =====");
    updateDuration(getBuildSQLClaus(startDateString, endDateString),
            "select plugin_key from rbt_plugin_count_in");

    System.out.println("[INFO] Total Time: " + (System.currentTimeMillis() - startRunningTime) + " ms.");
    System.out.println("[INFO] End executing BatchUpdateDurationJob...");
}

From source file:babel.prep.datedcorpus.DatedLangFilesOutputFormat.java

protected String generateFileNameForKeyValue(Text key, Text ver, String name) {
    String toks[] = key.toString().split(DatedCorpusGenMapper.DATE_LANG_SEP);

    if (toks == null || toks.length != 2) {
        return REJECTED_FILE;
    } else {/* w  w w .j av a 2  s .c om*/
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(Long.parseLong(toks[1]));

        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1;
        int day = cal.get(Calendar.DAY_OF_MONTH);

        if (year < 2000 || year > 2011) {
            return REJECTED_FILE;
        } else {
            return toks[0] + File.separator + year + File.separator + year + "-" + month + "-" + day
                    + EXTENSION;
        }
    }
}

From source file:net.orpiske.dcd.collector.dataset.impl.MBoxDataSetTest.java

@Test
public void testOneDigitDateWithTZ() {
    Data data = dataList.get(0);/*from   w ww .  jav  a2  s .  c  o m*/

    Date date = data.getDate();
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);

    assertEquals("The year is incorrect", 2013, cal.get(Calendar.YEAR));
    assertEquals("The month is incorrect", Calendar.MAY, cal.get(Calendar.MONTH));
    assertEquals("The day is incorrect", 2, cal.get(Calendar.DAY_OF_MONTH));
}

From source file:com.hybris.datahub.outbound.utils.CommonUtils.java

/**
 * Get all dates within three months//w  w  w  .ja  va  2s  . com
 *
 * @param startDate
 * @param nowDate
 *
 * @return Sample Data:
 *         <p>
 *         key:value-->start:2001-01-01 00:00:00 <br>
 *         or <br>
 *         end:2001-01-01 23:59:59 <br>
 */
public static List<Map<String, Date>> findDates(Date startDate, Date nowDate) {
    final List<Map<String, Date>> lDate = new ArrayList<Map<String, Date>>();
    final SimpleDateFormat ymd = new SimpleDateFormat("yyyy-MM-dd");
    final SimpleDateFormat ymdmhs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    final Calendar calendar = Calendar.getInstance();
    if (nowDate == null && startDate == null) {

        nowDate = calendar.getTime();
        calendar.add(Calendar.MONTH, -3);
        startDate = calendar.getTime();
    } else if (nowDate != null && startDate == null) {

        calendar.add(Calendar.MONTH, -3);
        startDate = calendar.getTime();

    } else if (nowDate == null && startDate != null) {
        nowDate = calendar.getTime();
    }

    try {
        final Map<String, Date> beginItem = new HashMap<String, Date>();
        beginItem.put("start", ymdmhs.parse(ymd.format(startDate) + " 00:00:00"));
        beginItem.put("end", ymdmhs.parse(ymd.format(startDate) + " 23:59:59"));

        lDate.add(beginItem);

        final Calendar calBegin = Calendar.getInstance();
        calBegin.setTime(startDate);

        final Calendar calEnd = Calendar.getInstance();
        calEnd.setTime(startDate);

        while (ymd.parse(ymd.format(nowDate)).after(calBegin.getTime())) {
            calBegin.add(Calendar.DAY_OF_MONTH, 1);
            final Map<String, Date> dateItem = new HashMap<String, Date>();

            dateItem.put("start", ymdmhs.parse(ymd.format(calBegin.getTime()) + " 00:00:00"));
            dateItem.put("end", ymdmhs.parse(ymd.format(calBegin.getTime()) + " 23:59:59"));

            lDate.add(dateItem);
        }
    } catch (final ParseException e) {
        LOGGER.error(e.getMessage());
    }
    return lDate;
}

From source file:com.augmentum.common.util.DateUtil.java

public static int getDaysBetween(Date startDate, Date endDate, TimeZone timeZone) {

    Calendar startCal = new GregorianCalendar(timeZone);
    startCal.setTime(DateUtils.truncate(startDate, Calendar.DAY_OF_MONTH));

    Calendar endCal = new GregorianCalendar(timeZone);
    endCal.setTime(DateUtils.truncate(endDate, Calendar.DAY_OF_MONTH));

    int daysBetween = 0;
    while (startCal.before(endCal)) {
        daysBetween++;// www. j  a v a2 s. c om

        startCal.add(Calendar.DAY_OF_MONTH, 1);
    }

    return daysBetween;
}

From source file:org.openmrs.module.uiframeworkpatientsummarysupport.fragment.controller.PatientObsFlowsheetFragmentController.java

public void controller(FragmentModel model, @FragmentParam(value = "patientId") Patient patient,
        @FragmentParam(value = "conceptIds") ArrayList<Concept> questionConcepts,
        @FragmentParam(value = "withinDays", required = false) Integer withinDays,
        @FragmentParam(value = "maximumNumber", required = false) Integer maximumNumber) {

    List<Person> persons = new ArrayList<Person>();
    persons.add(patient);//  w  w  w  .  j a  va  2  s .  co  m

    List<PERSON_TYPE> personTypes = new ArrayList<PERSON_TYPE>();
    personTypes.add(PERSON_TYPE.PATIENT);

    //we want the latest obs to be displayed at the top
    List<String> sortList = new ArrayList<String>();
    sortList.add("obsDatetime");

    Date fromDate = null;
    if (withinDays != null) {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DAY_OF_MONTH, -withinDays);
        fromDate = startOfDay(cal.getTime());
    }

    List<Obs> observations = Context.getObsService().getObservations(persons, null, questionConcepts, null,
            personTypes, null, sortList, null, null, fromDate, null, false);
    if (maximumNumber != null)
        observations = observations.subList(0, maximumNumber);

    Map<Concept, List<Obs>> conceptObsMap = new HashMap<Concept, List<Obs>>();
    for (Obs o : observations) {
        if (!conceptObsMap.containsKey(o.getConcept()))
            conceptObsMap.put(o.getConcept(), new ArrayList<Obs>());

        conceptObsMap.get(o.getConcept()).add(o);
    }

    model.addAttribute("conceptObsMap", conceptObsMap);
}