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:DateCalAdd.java

public static void main(String[] av) {
    /** Today's date */
    Calendar now = Calendar.getInstance();

    /* Do "DateFormat" using "simple" format. */
    SimpleDateFormat formatter = new SimpleDateFormat("E yyyy/MM/dd 'at' hh:mm:ss a zzz");
    System.out.println("It is now " + formatter.format(now.getTime()));

    now.add(Calendar.YEAR, -2);
    System.out.println("Two years ago was " + formatter.format(now.getTime()));
}

From source file:com.cjwagner.InfoSecPriv.ExtensionServer.java

public static void main(String[] args) {
    initializeLogStore();/*  ww  w.  ja  v a2s . c o m*/

    get("/data", (request, response) -> {
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        cal.add(Calendar.MINUTE, -5);
        Date tMinusDelta = cal.getTime();

        Map<String, LoggerMessage> filtered = new HashMap<String, LoggerMessage>();
        for (Map.Entry<String, LoggerMessage> entry : logStore.entrySet()) {
            String ip = entry.getKey();
            LoggerMessage logmess = entry.getValue();
            LoggerMessage logmessFiltered = new LoggerMessage();
            logmessFiltered.setFirstLogTime(logmess.getFirstLogTime());
            List<LogData> filteredData = new ArrayList<LogData>();
            logmessFiltered.setLogs(filteredData);
            for (LogData data : logmess.getLogs()) {
                if (data.getDate().after(tMinusDelta)) {
                    filteredData.add(data);
                }
            }

            filtered.put(ip, logmessFiltered);
        }

        ObjectMapper objMapper = new ObjectMapper().configure(SerializationFeature.INDENT_OUTPUT, true);
        String jsonResponse = objMapper.writeValueAsString(filtered);
        System.out.println("Responded to query for recent data from IP: " + request.ip());
        return jsonResponse;
    });

    post("/LicenseRegistry", (request, response) -> {
        if (storeSize >= MAXSTORESIZE) {
            response.status(507);//insufficient storage
            return "Server storage full!";
        }

        String ip = request.ip().replace(':', '_');
        String json = request.body();

        try {
            LoggerMessage logMess = LoggerMessage.fromJSON(json);
            logMess.setFirstLogTime(new Date());
            LoggerMessage rec = logStore.get(ip);
            if (rec == null) {
                logStore.put(ip, logMess);
                rec = logMess;
            } else {
                rec.getLogs().addAll(logMess.getLogs());
            }
            updateLogFile(ip, rec);
            storeSize += logMess.getLogs().size();
            response.status(200);

            System.out.println("Recieved log data from IP: " + ip);
            return "LicenseKey:<c706cfe7-b748-4d75-98b5-c6b32ab789cb>";
        } catch (JsonParseException jpe) {
            response.status(HTTP_BAD_REQUEST);
            System.out.println("Failed to parse log data from IP: " + ip);
            return jpe.getMessage();
        }
    });
}

From source file:UploadUrlGenerator.java

public static void main(String[] args) throws Exception {
    Options opts = new Options();

    opts.addOption(Option.builder().longOpt(ENDPOINT_OPTION).required().hasArg().argName("url")
            .desc("Sets the ECS S3 endpoint to use, e.g. https://ecs.company.com:9021").build());
    opts.addOption(Option.builder().longOpt(ACCESS_KEY_OPTION).required().hasArg().argName("access-key")
            .desc("Sets the Access Key (user) to sign the request").build());
    opts.addOption(Option.builder().longOpt(SECRET_KEY_OPTION).required().hasArg().argName("secret")
            .desc("Sets the secret key to sign the request").build());
    opts.addOption(Option.builder().longOpt(BUCKET_OPTION).required().hasArg().argName("bucket-name")
            .desc("The bucket containing the object").build());
    opts.addOption(Option.builder().longOpt(KEY_OPTION).required().hasArg().argName("object-key")
            .desc("The object name (key) to access with the URL").build());
    opts.addOption(Option.builder().longOpt(EXPIRES_OPTION).hasArg().argName("minutes")
            .desc("Minutes from local time to expire the request.  1 day = 1440, 1 week=10080, "
                    + "1 month (30 days)=43200, 1 year=525600.  Defaults to 1 hour (60).")
            .build());/* w w  w. j ava2  s  . c o  m*/
    opts.addOption(Option.builder().longOpt(VERB_OPTION).hasArg().argName("http-verb").type(HttpMethod.class)
            .desc("The HTTP verb that will be used with the URL (PUT, GET, etc).  Defaults to GET.").build());
    opts.addOption(Option.builder().longOpt(CONTENT_TYPE_OPTION).hasArg().argName("mimetype")
            .desc("Sets the Content-Type header (e.g. image/jpeg) that will be used with the request.  "
                    + "Must match exactly.  Defaults to application/octet-stream for PUT/POST and "
                    + "null for all others")
            .build());

    DefaultParser dp = new DefaultParser();

    CommandLine cmd = null;
    try {
        cmd = dp.parse(opts, args);
    } catch (ParseException e) {
        System.err.println("Error: " + e.getMessage());
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp("java -jar UploadUrlGenerator-xxx.jar", opts, true);
        System.exit(255);
    }

    URI endpoint = URI.create(cmd.getOptionValue(ENDPOINT_OPTION));
    String accessKey = cmd.getOptionValue(ACCESS_KEY_OPTION);
    String secretKey = cmd.getOptionValue(SECRET_KEY_OPTION);
    String bucket = cmd.getOptionValue(BUCKET_OPTION);
    String key = cmd.getOptionValue(KEY_OPTION);
    HttpMethod method = HttpMethod.GET;
    if (cmd.hasOption(VERB_OPTION)) {
        method = HttpMethod.valueOf(cmd.getOptionValue(VERB_OPTION).toUpperCase());
    }
    int expiresMinutes = 60;
    if (cmd.hasOption(EXPIRES_OPTION)) {
        expiresMinutes = Integer.parseInt(cmd.getOptionValue(EXPIRES_OPTION));
    }
    String contentType = null;
    if (method == HttpMethod.PUT || method == HttpMethod.POST) {
        contentType = "application/octet-stream";
    }

    if (cmd.hasOption(CONTENT_TYPE_OPTION)) {
        contentType = cmd.getOptionValue(CONTENT_TYPE_OPTION);
    }

    BasicAWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
    ClientConfiguration cc = new ClientConfiguration();
    // Force use of v2 Signer.  ECS does not support v4 signatures yet.
    cc.setSignerOverride("S3SignerType");
    AmazonS3Client s3 = new AmazonS3Client(credentials, cc);
    s3.setEndpoint(endpoint.toString());
    S3ClientOptions s3c = new S3ClientOptions();
    s3c.setPathStyleAccess(true);
    s3.setS3ClientOptions(s3c);

    // Sign the URL
    Calendar c = Calendar.getInstance();
    c.add(Calendar.MINUTE, expiresMinutes);
    GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(bucket, key).withExpiration(c.getTime())
            .withMethod(method);
    if (contentType != null) {
        req = req.withContentType(contentType);
    }
    URL u = s3.generatePresignedUrl(req);
    System.out.printf("URL: %s\n", u.toURI().toASCIIString());
    System.out.printf("HTTP Verb: %s\n", method);
    System.out.printf("Expires: %s\n", c.getTime());
    System.out.println("To Upload with curl:");

    StringBuilder sb = new StringBuilder();
    sb.append("curl ");

    if (method != HttpMethod.GET) {
        sb.append("-X ");
        sb.append(method.toString());
        sb.append(" ");
    }

    if (contentType != null) {
        sb.append("-H \"Content-Type: ");
        sb.append(contentType);
        sb.append("\" ");
    }

    if (method == HttpMethod.POST || method == HttpMethod.PUT) {
        sb.append("-T <filename> ");
    }

    sb.append("\"");
    sb.append(u.toURI().toASCIIString());
    sb.append("\"");

    System.out.println(sb.toString());

    System.exit(0);
}

From source file:com.appeligo.epg.EpgIndexer.java

public static void main(String[] args) throws Exception {
    HessianProxyFactory factory = new HessianProxyFactory();
    EPGProvider epg = (EPGProvider) factory.create(EPGProvider.class, "http://localhost/epg/channel.epg");
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.HOUR, -5);
    cal.set(Calendar.DATE, 1);/*from  www . ja va 2s . c  o m*/
    String[] lineups = new String[] { "SDTW-C", "P-C", "P-DC", "P-S", "M-C", "M-DC", "M-S", "E-C", "E-DC",
            "E-S", "H-C", "H-DC", "H-S" };
    List<String> ids = epg.getModifiedProgramIds(cal.getTime());
    int count = 0;
    long average = 0;
    int counter = 0;
    int added = 0;
    while (count < ids.size()) {
        System.err.println("in loop: " + counter + ", " + count + "," + ids.size());
        int subsetSize = (ids.size() < 100 ? ids.size() : 100);
        counter++;
        if (count % 1000 == 0) {
            log.debug("Index programs into the Lucene Index. Current have processed " + count
                    + " programs out of " + ids.size());
        }
        int endIndex = (count + subsetSize > ids.size() ? ids.size() : count + subsetSize);
        List<String> subset = ids.subList(count, endIndex);
        count += subsetSize;

        long time = System.currentTimeMillis();
        HashMap<String, List<ScheduledProgram>> schedules = new HashMap<String, List<ScheduledProgram>>();
        for (String lineup : lineups) {
            ScheduledProgram[] programs = epg.getNextShowingList(lineup, subset);
            for (ScheduledProgram program : programs) {
                if (program != null) {
                    List<ScheduledProgram> schedule = schedules.get(program.getProgramId());
                    if (schedule == null) {
                        schedule = new ArrayList<ScheduledProgram>();
                        schedules.put(program.getProgramId(), schedule);
                    }
                    schedule.add(program);
                    added++;
                }
            }
        }
        long after = System.currentTimeMillis();
        long diff = after - time;
        average += diff;
        System.err.println(diff + " - " + (average / counter) + " added: " + added);
    }
    //      EpgIndexer indexer = new EpgIndexer(programIndex, epg, lineup);
    //      Calendar cal = Calendar.getInstance();
    //      cal.set(Calendar.DAY_OF_MONTH, 24);
    //      cal.set(Calendar.HOUR_OF_DAY, 0);
    //      indexer.updateEpgIndex(cal.getTime());
}

From source file:Main.java

public static void main(String[] args) {
    Calendar now = Calendar.getInstance();
    System.out.println("Current Date : " + (now.get(Calendar.MONTH) + 1) + "-" + now.get(Calendar.DATE) + "-"
            + now.get(Calendar.YEAR));
    System.out.println("Current time : " + now.get(Calendar.HOUR_OF_DAY) + ":" + now.get(Calendar.MINUTE) + ":"
            + now.get(Calendar.SECOND));

    now.add(Calendar.HOUR, 10);
    System.out.println("New time after adding 10 hours : " + now.get(Calendar.HOUR_OF_DAY) + ":"
            + now.get(Calendar.MINUTE) + ":" + now.get(Calendar.SECOND));
}

From source file:Main.java

public static void main(String[] args) {
    Calendar now = Calendar.getInstance();

    System.out.println("Current date : " + (now.get(Calendar.MONTH) + 1) + "-" + now.get(Calendar.DATE) + "-"
            + now.get(Calendar.YEAR));

    System.out.println("Current week of month is : " + now.get(Calendar.WEEK_OF_MONTH));
    System.out.println("Current week of year is : " + now.get(Calendar.WEEK_OF_YEAR));

    now.add(Calendar.WEEK_OF_YEAR, 1);
    System.out.println("date after one week : " + (now.get(Calendar.MONTH) + 1) + "-" + now.get(Calendar.DATE)
            + "-" + now.get(Calendar.YEAR));
}

From source file:Main.java

public static void main(String[] args) {
    Calendar now = Calendar.getInstance();
    System.out.println("Current Date : " + (now.get(Calendar.MONTH) + 1) + "-" + now.get(Calendar.DATE) + "-"
            + now.get(Calendar.YEAR));
    System.out.println("Current time : " + now.get(Calendar.HOUR_OF_DAY) + ":" + now.get(Calendar.MINUTE) + ":"
            + now.get(Calendar.SECOND));

    now = Calendar.getInstance();
    now.add(Calendar.HOUR, -3);
    System.out.println("Time before 3 hours : " + now.get(Calendar.HOUR_OF_DAY) + ":" + now.get(Calendar.MINUTE)
            + ":" + now.get(Calendar.SECOND));
}

From source file:Main.java

public static void main(String[] args) {
    Calendar now = Calendar.getInstance();

    System.out.println("Current date : " + (now.get(Calendar.MONTH) + 1) + "-" + now.get(Calendar.DATE) + "-"
            + now.get(Calendar.YEAR));

    System.out.println("Current week of month is : " + now.get(Calendar.WEEK_OF_MONTH));
    System.out.println("Current week of year is : " + now.get(Calendar.WEEK_OF_YEAR));

    now = Calendar.getInstance();
    now.add(Calendar.WEEK_OF_YEAR, -50);
    System.out.println("date before 50 weeks : " + (now.get(Calendar.MONTH) + 1) + "-" + now.get(Calendar.DATE)
            + "-" + now.get(Calendar.YEAR));
}

From source file:info.usbo.skypetwitter.Run.java

public static void main(String[] args) {
    System.out.println("Working Directory = " + System.getProperty("user.dir"));
    Properties props;/*from w w  w .  j a  v a 2s.  c  o m*/
    props = (Properties) System.getProperties().clone();
    //loadProperties(props, "D:\\Data\\Java\\classpath\\twitter.props");
    work_dir = System.getProperty("user.dir");
    loadProperties(props, work_dir + "\\twitter.props");
    twitter_user_id = props.getProperty("twitter.user");
    twitter_timeout = Integer.parseInt(props.getProperty("twitter.timeout"));
    System.out.println("Twitter user: " + twitter_user_id);
    System.out.println("Twitter timeout: " + twitter_timeout);
    if ("".equals(twitter_user_id)) {
        return;
    }
    if (load_file() == 0) {
        System.out.println("File not found");
        return;
    }
    while (true) {
        bChanged = 0;
        /*
        create_id();
        Chat ch = Chat.getInstance(chat_group_id);
        ch.send("!");
        */
        SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm");
        System.out.println("Looking at " + sdf.format(Calendar.getInstance().getTime()));
        Chat ch = Chat.getInstance(chat_group_id);
        Twitter twitter = new TwitterFactory().getInstance();
        try {
            List<Status> statuses;
            statuses = twitter.getUserTimeline(twitter_user_id);
            //System.out.println("Showing @" + twitter_user_id + "'s user timeline.");
            String sText;
            for (Status status : statuses) {
                //System.out.println(status.getId());
                Date d = status.getCreatedAt();
                //   ?
                Calendar cal = Calendar.getInstance();
                cal.setTime(d);
                cal.add(Calendar.HOUR_OF_DAY, 7);
                d = cal.getTime();
                sText = "@" + status.getUser().getScreenName() + "  " + sdf.format(d)
                        + " ( https://twitter.com/" + twitter_user_id + "/status/" + status.getId() + " ): \r\n"
                        + status.getText() + "\r\n***";
                for (URLEntity e : status.getURLEntities()) {
                    sText = sText.replaceAll(e.getURL(), e.getExpandedURL());
                }
                for (MediaEntity e : status.getMediaEntities()) {
                    sText = sText.replaceAll(e.getURL(), e.getMediaURL());
                }
                if (twitter_ids.indexOf(status.getId()) == -1) {
                    System.out.println(sText);
                    ch.send(sText);
                    twitter_ids.add(status.getId());
                    bChanged = 1;
                }
            }
        } catch (TwitterException te) {
            te.printStackTrace();
            System.out.println("Failed to get timeline: " + te.getMessage());
            //System.exit(-1);
        } catch (SkypeException ex) {
            ex.printStackTrace();
            System.out.println("Failed to send message: " + ex.getMessage());
        }

        // VK
        try {
            vk();
            for (VK v : vk) {
                if (vk_ids.indexOf(v.getId()) == -1) {
                    Date d = v.getDate();
                    //   ?
                    Calendar cal = Calendar.getInstance();
                    cal.setTime(d);
                    cal.add(Calendar.HOUR_OF_DAY, 7);
                    d = cal.getTime();
                    String sText = "@Depersonilized (VK)  " + sdf.format(d)
                            + " ( http://vk.com/Depersonilized?w=wall-0_" + v.getId() + " ): \r\n"
                            + v.getText();
                    if (!"".equals(v.getAttachment())) {
                        sText += "\r\n" + v.getAttachment();
                    }
                    sText += "\r\n***";
                    System.out.println(sText);
                    ch.send(sText);
                    vk_ids.add(v.getId());
                    bChanged = 1;
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
            System.out.println("Failed to get vk: " + e.getMessage());
            //System.exit(-1);
        } catch (SkypeException ex) {
            ex.printStackTrace();
            System.out.println("Failed to send message: " + ex.getMessage());
        }
        if (bChanged == 1) {
            save_file();
        }
        try {
            Thread.sleep(1000 * 60 * twitter_timeout);
        } catch (InterruptedException ex) {
            ex.printStackTrace();
            System.out.println("Failed to sleep: " + ex.getMessage());
        }
    }
}

From source file:de.codesourcery.eve.skills.ui.utils.CalendarWidget.java

public static void main(String[] args) throws Exception {

    final SimpleDateFormat DF = new SimpleDateFormat("dd.MM");

    final Calendar specialDate = Calendar.getInstance();
    specialDate.add(Calendar.DAY_OF_MONTH, 5);

    final AtomicBoolean doStuff = new AtomicBoolean(false);

    final ICalendarRenderer renderer = new ICalendarRenderer() {

        @Override//w ww. j  a v  a2s.  c  om
        public String getDateLabel(Date date) {
            return DF.format(date);
        }

        @Override
        public String getText(Date date) {
            if (DateUtils.isSameDay(date, specialDate.getTime()) && doStuff.get()) {
                return "SPECIAL !!!";
            }
            return "some\nmultiline\ntext";
        }

        @Override
        public String getToolTip(Date date) {
            return getText(date);
        }

        @Override
        public Color getTextColor(Date date) {
            return Color.RED;
        }
    };

    final JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(new GridBagLayout());

    final CalendarWidget widget = new CalendarWidget(new Date(), renderer);

    widget.addSelectionListener(new ISelectionListener<Date>() {

        @Override
        public void selectionChanged(Date selected) {
            System.out.println("Selected date > " + selected);
        }
    });
    frame.getContentPane().add(widget, new ConstraintsBuilder().end());
    frame.pack();
    frame.setVisible(true);

    java.lang.Thread.sleep(2 * 1000);
    doStuff.set(true);
    widget.refreshDateLabel(specialDate.getTime());

}