Example usage for java.util Calendar add

List of usage examples for java.util Calendar add

Introduction

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

Prototype

public abstract void add(int field, int amount);

Source Link

Document

Adds or subtracts the specified amount of time to the given calendar field, based on the calendar's rules.

Usage

From source file:com.clustercontrol.systemlog.bean.SyslogMessage.java

/**
 * syslog????????SyslogMessage????API<br>
 * <br>/*  ww w  . j  av a 2  s  . com*/
 * <b>???</b><br>
 * 1. ???????????????<br>
 * 2. ???????????<br>
 * @param syslog syslog?
 * @return SyslogMessage
 * @throws ParseException syslog???????????
 * @throws HinemosUnknown 
 */
public static SyslogMessage parse(String syslog) throws ParseException, HinemosUnknown {
    if (log.isDebugEnabled()) {
        log.debug("parsing syslog : " + syslog);
    }

    // [0]:, [1]:(MMM), [2]:(dd), [3]:(HH), [4]:(mm), [5]:(ss), [6]:??, [7]:
    // ?{1,date,MMM dd HH:mm:ss}????????????1970????
    // ????????2/29???3/1?????(1970???????)
    MessageFormat syslogFormat = new MessageFormat("<{0,number,integer}>{1} {2} {3}:{4}:{5} {6} {7}",
            Locale.ENGLISH);

    // ??????
    Object[] syslogArgs = syslogFormat.parse(syslog);

    // RFC3164??????????????????
    if ("".equals(syslogArgs[SYSLOG_FORMAT_DAY])) {
        syslogFormat = new MessageFormat("<{0,number,integer}>{1}  {2} {3}:{4}:{5} {6} {7}", Locale.ENGLISH);
        syslogArgs = syslogFormat.parse(syslog);
    }

    if (syslogArgs == null)
        throw new HinemosUnknown("different syslog pattern");

    if (log.isDebugEnabled()) {
        int i = 0;
        for (Object arg : syslogArgs) {
            log.debug(String.format("syslog args [%d] : %s", i++, arg.toString()));
        }
    }

    // ???????(H)
    Integer syslogEffectiveTime = HinemosPropertyUtil
            .getHinemosPropertyNum("monitor.systemlog.period.hour", Long.valueOf(SYSLOG_DEFAULT_PERIOD_HOUR))
            .intValue();

    // 0???????????
    if (syslogEffectiveTime <= 0) {
        syslogEffectiveTime = SYSLOG_DEFAULT_PERIOD_HOUR;
    }

    Calendar nowCal = HinemosTime.getCalendarInstance();

    // ??(?)
    int year = nowCal.get(Calendar.YEAR) + 1;
    int month = editCalendarMonth((String) syslogArgs[SYSLOG_FORMAT_MONTH]);
    int dayOfMonth = Integer.parseInt((String) syslogArgs[SYSLOG_FORMAT_DAY]);
    int hourOfDay = Integer.parseInt((String) syslogArgs[SYSLOG_FORMAT_HH]);
    int minute = Integer.parseInt((String) syslogArgs[SYSLOG_FORMAT_MM]);
    int second = Integer.parseInt((String) syslogArgs[SYSLOG_FORMAT_SS]);

    // ?
    List<Calendar> checkCalList = new ArrayList<Calendar>();
    // (??
    Calendar syslogEffectiveCal = (Calendar) nowCal.clone();
    syslogEffectiveCal.add(Calendar.HOUR, syslogEffectiveTime);

    // ???
    for (int i = 0; checkCalList.size() < 2; i++) {

        // ??????
        if (LEAPYEAR_CHECK_COUNT <= i) {
            break;
        }
        Calendar syslogCheckCal = new GregorianCalendar(year, month, dayOfMonth, hourOfDay, minute, second);
        year--;

        // ???????(??)
        if (syslogEffectiveCal.compareTo(syslogCheckCal) < 0) {
            continue;
        }
        // ??????????????
        if (dayOfMonth != syslogCheckCal.get(Calendar.DAY_OF_MONTH)) {
            continue;
        }
        // ????
        checkCalList.add(syslogCheckCal);
    }

    Calendar editSyslogCal = null;

    // ?????
    if (checkCalList.size() > 0) {
        long absMinMillis = Long.MAX_VALUE;
        for (int i = 0; i < checkCalList.size(); i++) {
            long absDiff = Math.abs(checkCalList.get(i).getTimeInMillis() - nowCal.getTimeInMillis());
            if (absDiff < absMinMillis) {
                // ??????
                absMinMillis = absDiff;
                editSyslogCal = checkCalList.get(i);
            }
        }
    } else {
        // ??????
        editSyslogCal = new GregorianCalendar(nowCal.get(Calendar.YEAR), month, dayOfMonth, hourOfDay, minute,
                second);
        log.warn("System log date is invalid : " + syslog);
    }

    int pri = ((Long) syslogArgs[SYSLOG_FORMAT_PRIORITY]).intValue();
    String hostname = (String) syslogArgs[SYSLOG_FORMAT_HOSTNAME];
    String msg = (String) syslogArgs[SYSLOG_FORMAT_MESSAGE];
    Date date = editSyslogCal.getTime();

    // ??
    SyslogMessage instance = new SyslogMessage(getFacility((int) pri), getSeverity((int) pri), date.getTime(),
            hostname, msg, syslog);
    if (log.isDebugEnabled()) {
        log.debug("parsed syslog : " + instance);
    }

    return instance;
}

From source file:net.kourlas.voipms_sms.Utils.java

/**
 * Formats a date for display in the application.
 *
 * @param applicationContext The application context.
 * @param date               The date to format.
 * @param hideTime           Omits the time in the formatted date if true.
 * @return the formatted date./*w  w w . j a v  a2  s  .  co m*/
 */
public static String getFormattedDate(Context applicationContext, Date date, boolean hideTime) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);

    Calendar oneMinuteAgo = Calendar.getInstance();
    oneMinuteAgo.add(Calendar.MINUTE, -1);
    if (oneMinuteAgo.getTime().before(date)) {
        // Last minute: X seconds ago
        long seconds = (Calendar.getInstance().getTime().getTime() - calendar.getTime().getTime()) / 1000;
        if (seconds < 10) {
            return applicationContext.getString(R.string.utils_date_just_now);
        } else {
            return seconds + " " + applicationContext.getString(R.string.utils_date_seconds_ago);
        }
    }

    Calendar oneHourAgo = Calendar.getInstance();
    oneHourAgo.add(Calendar.HOUR_OF_DAY, -1);
    if (oneHourAgo.getTime().before(date)) {
        // Last hour: X minutes ago
        long minutes = (Calendar.getInstance().getTime().getTime() - calendar.getTime().getTime())
                / (1000 * 60);
        if (minutes == 1) {
            return applicationContext.getString(R.string.utils_date_one_minute_ago);
        } else {
            return minutes + " " + applicationContext.getString(R.string.utils_date_minutes_ago);
        }
    }

    if (compareDateWithoutTime(Calendar.getInstance(), calendar) == 0) {
        // Today: h:mm a
        DateFormat format = new SimpleDateFormat("h:mm a", Locale.getDefault());
        return format.format(date);
    }

    if (Calendar.getInstance().get(Calendar.WEEK_OF_YEAR) == calendar.get(Calendar.WEEK_OF_YEAR)
            && Calendar.getInstance().get(Calendar.YEAR) == calendar.get(Calendar.YEAR)) {
        if (hideTime) {
            // This week: EEE
            DateFormat format = new SimpleDateFormat("EEE", Locale.getDefault());
            return format.format(date);
        } else {
            // This week: EEE h:mm a
            DateFormat format = new SimpleDateFormat("EEE h:mm a", Locale.getDefault());
            return format.format(date);
        }
    }

    if (Calendar.getInstance().get(Calendar.YEAR) == calendar.get(Calendar.YEAR)) {
        if (hideTime) {
            // This year: MMM d
            DateFormat format = new SimpleDateFormat("MMM d", Locale.getDefault());
            return format.format(date);
        } else {
            // This year: MMM d h:mm a
            DateFormat format = new SimpleDateFormat("MMM d, h:mm a", Locale.getDefault());
            return format.format(date);
        }
    }

    if (hideTime) {
        // Any: MMM d, yyyy
        DateFormat format = new SimpleDateFormat("MMM d, yyyy", Locale.getDefault());
        return format.format(date);
    } else {
        // Any: MMM d, yyyy h:mm a
        DateFormat format = new SimpleDateFormat("MMM d, yyyy, h:mm a", Locale.getDefault());
        return format.format(date);
    }
}

From source file:com.linuxbox.enkive.teststats.StatsMonthGrainTest.java

@BeforeClass
public static void setUp() throws ParseException, GathererException {
    coll = TestHelper.GetTestCollection();
    client = TestHelper.BuildClient();/*from   ww  w . j a  va 2s  .  c om*/
    grain = new MonthConsolidator(client);

    // clean up if week was run...
    Map<String, Object> queryMap = new HashMap<String, Object>();
    queryMap.put(CONSOLIDATION_TYPE, CONSOLIDATION_DAY);
    StatsQuery statsQuery = new MongoStatsQuery(null, CONSOLIDATION_DAY, null);
    Set<Object> ids = new HashSet<Object>();
    for (Map<String, Object> mapToDelete : client.queryStatistics(statsQuery)) {
        ids.add(mapToDelete.get("_id"));
    }

    if (!ids.isEmpty()) {
        client.remove(ids);
    }

    // TODO
    List<Map<String, Object>> stats = (new DayConsolidator(client)).consolidateData();
    Map<String, Object> timeMap = new HashMap<String, Object>();
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.MILLISECOND, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.HOUR, 0);
    cal.set(Calendar.DAY_OF_MONTH, 1);
    for (int i = 0; i < 10; i++) {
        if (i == 5) {
            cal.add(Calendar.MONTH, -1);
        }
        timeMap.put(CONSOLIDATION_MAX, cal.getTime());
        timeMap.put(CONSOLIDATION_MIN, cal.getTime());
        for (Map<String, Object> data : stats) {
            data.put(STAT_TIMESTAMP, timeMap);
        }
        client.storeData(stats);
    }
    dataCount = coll.count();
}

From source file:erpsystem.chart.Charts.java

/** Grfico criado para mostrar o histrico de
 * faturamento periodicamente considerando o valor bruto
 * em R$ de lucro.//w ww  . ja va 2 s.c om
*/

public static BufferedImage create002(int w, int h, Calendar initialCalendar, int interval) {
    //Inicio
    DefaultCategoryDataset ds = new DefaultCategoryDataset();
    String LUCRO = "Lucro R$";

    //Configurando os Calendars.
    Calendar finalCalendar = getCurrentCalendar();
    Calendar finalValue = copyCalendar(initialCalendar);
    Calendar initialValue = copyCalendar(initialCalendar);

    while (finalCalendar.after(finalValue)) {

        //ajustando os Calendars ponteiros.
        initialValue = copyCalendar(finalValue);
        finalValue.add(Calendar.DAY_OF_MONTH, interval);

        //toString para depurao.
        String s1 = toString(initialValue);
        String s2 = toString(finalValue);

        //Obtendo as datas como raw para 
        //possibilitar comparao com o banco de dados.
        long value1 = initialValue.getTimeInMillis();
        long value2 = finalValue.getTimeInMillis();

        //Obtendo a nova abstrao de lucro com os intervalos especificados.
        double lucro = Chart001.getValorLucroEm(value1, value2);
        double venda = Chart001.getValorVendaEm(value1, value2);
        double compra = Chart001.getValorCompraEm(value1, value2);

        //Adicionando a nova abstrao na coleo de dados do grfico.
        int y = initialValue.get(Calendar.YEAR);
        int m = initialValue.get(Calendar.MONTH) + 1;
        int d = initialValue.get(Calendar.DAY_OF_MONTH);
        String identifier = d + "/" + m + "/" + y;
        ds.addValue(lucro, "Lucro", identifier);
        ds.addValue(venda, "Venda", identifier);
        ds.addValue(compra, "Compra", identifier);

    }

    //Criando o grfico abstrato em 3D.
    JFreeChart chart = ChartFactory.createBarChart3D("Faturamento", "Faturamento", "Valor R$", ds,
            PlotOrientation.VERTICAL, true, true, false);

    //Criando e retornando a imagem como 
    //mapa de pixels do grfico.
    return chart.createBufferedImage(w, h);
}

From source file:Main.java

@SuppressLint("SimpleDateFormat")
static String futureDate() {
    // take current date and increment
    Calendar cal = Calendar.getInstance(TimeZone.getDefault());
    Date currentLocalTime = cal.getTime();
    SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd");
    date.setTimeZone(TimeZone.getDefault());
    _currentDate = date.format(currentLocalTime);
    try {/*from   w ww .j  a  v a 2  s .  co m*/
        cal.setTime(date.parse(_currentDate));
    } catch (ParseException e) {
        e.printStackTrace();
    }
    cal.add(Calendar.DATE, 30);
    _currentDate = date.format(cal.getTime());
    return _currentDate;
}

From source file:com.inmobi.messaging.consumer.util.HadoopUtil.java

static Date getCommitDateForFile(String fileName, Date minuteDirTimeStamp) throws IOException {
    Calendar cal = Calendar.getInstance();
    if (minuteDirTimeStamp == null) {
        cal.setTime(startCommitTime);//from   w w  w  .  ja  va 2  s  .c om
    } else {
        cal.setTime(minuteDirTimeStamp);
    }
    LOG.debug("index for " + fileName + ":" + getIndex(fileName));
    cal.add(Calendar.MINUTE, getIndex(fileName));
    cal.add(Calendar.MINUTE, increment);
    LOG.debug("Commit time for file:" + fileName + " is " + cal.getTime());
    return cal.getTime();
}

From source file:freebase.api.FreebaseAPI.java

public static void FetchingFromGoogleAPI() {

    int max_step = 1;
    int step = 0;

    int month_step = 1;
    Calendar last_date = Calendar.getInstance();
    last_date.set(Calendar.YEAR, 2016);
    last_date.set(Calendar.MONTH, 0);
    last_date.set(Calendar.DAY_OF_MONTH, 1);

    Calendar from_date = Calendar.getInstance();
    from_date.set(Calendar.YEAR, 2010);
    from_date.set(Calendar.MONTH, 0);
    from_date.set(Calendar.DAY_OF_MONTH, 1);

    Calendar to_date = (Calendar) from_date.clone();
    to_date.add(Calendar.MONTH, month_step);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    while (true) {
        //            if (step > max_step) {
        //                break;
        //            }
        //            System.out.println(">>> Cursor = " + current_cursor);
        //            if (/*films == null || films.isEmpty() ||*/step == max_step) {
        //                System.out.println("Films is null or zero size. Break.");
        //                break;
        //            }
        if (from_date.after(last_date)) {
            System.out.println("Date is after last date");
            break;
        }//  www  .j  a v  a2  s  . com
        String fromDate = sdf.format(from_date.getTime());
        String toDate = sdf.format(to_date.getTime());
        System.out.println(step + " ) fetch films from " + fromDate + " to " + toDate);
        step++;
        List<Film> films = getFilms(fromDate, toDate);
        System.out.println("Films#: " + films.size());
        writeToFiles(films);
        //            for (Film f : films) {
        //                System.out.println(f);
        //            }
        from_date.add(Calendar.MONTH, month_step);
        to_date.add(Calendar.MONTH, month_step);

    }
}

From source file:com.xumpy.timesheets.services.implementations.JobsSrvImpl.java

public static List<? extends Jobs> addZeroDates(List<? extends Jobs> jobs, String month, JobsGroup jobsGroup)
        throws ParseException {
    SimpleDateFormat dfOnlyDay = new SimpleDateFormat("dd");
    List<Jobs> allJobsInMonth = new ArrayList<Jobs>();

    SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
    Date startDate = df.parse("01/" + month);

    Calendar endDate = Calendar.getInstance();
    endDate.setTime(startDate);/*  ww w.j  a  v  a2 s . c om*/
    endDate.set(Calendar.DAY_OF_MONTH, endDate.getActualMaximum(Calendar.DAY_OF_MONTH));
    endDate.add(Calendar.DATE, 1);

    Calendar iteratorDate = Calendar.getInstance();
    iteratorDate.setTime(startDate);

    while (iteratorDate.before(endDate)) {
        boolean found = false;
        JobsSrvPojo jobsSrvPojo = new JobsSrvPojo();

        for (Jobs job : jobs) {
            if (df.format(job.getJobDate()).equals(df.format(iteratorDate.getTime()))) {
                found = true;
                jobsSrvPojo = new JobsSrvPojo(job);
            }
        }

        if (!found) {
            jobsSrvPojo.setJobDate(iteratorDate.getTime());
            jobsSrvPojo.setJobsGroup(new JobsGroupSrvPojo(jobsGroup));
            jobsSrvPojo.setWorkedHours("0");
            jobsSrvPojo.setWeekendDay(jobInWeekend(jobsSrvPojo));
        }
        jobsSrvPojo.setJobDay(dfOnlyDay.format(jobsSrvPojo.getJobDate()));
        allJobsInMonth.add(jobsSrvPojo);
        iteratorDate.add(Calendar.DATE, 1);
    }

    return allJobsInMonth;
}

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

/**
 * Get all dates within three months/*from  w w w .  j  ava2  s. 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.arvato.thoroughly.util.CommonUtils.java

/**
 * Get all dates within three months//from  w w  w  . j ava  2 s. co  m
 *
 * @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) {
    List<Map<String, Date>> lDate = new ArrayList<Map<String, Date>>();
    SimpleDateFormat ymd = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
    SimpleDateFormat ymdmhs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);

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

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

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

        while (ymd.parse(ymd.format(nowDate)).after(calBegin.getTime())) {
            calBegin.add(Calendar.DAY_OF_MONTH, 1);
            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 (ParseException e) {
        LOGGER.error(e.getMessage());
    }
    return lDate;
}