Example usage for java.util Calendar setTime

List of usage examples for java.util Calendar setTime

Introduction

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

Prototype

public final void setTime(Date date) 

Source Link

Document

Sets this Calendar's time with the given Date.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss yyy");
    Date date1 = sdf.parse("Thu Oct 03 07:47:22 2015");
    Date date2 = sdf.parse("Mon Jul 05 08:47:22 2015");

    System.out.println(sdf.format(date1));
    System.out.println(sdf.format(date2));

    Calendar cal1 = Calendar.getInstance();
    Calendar cal2 = Calendar.getInstance();
    cal1.setTime(date1);
    cal2.setTime(date2);//from   w ww . j av a 2  s.  co m

    if (cal1.after(cal2)) {
        System.out.println("Date1 is after Date2");
    }

    if (cal1.before(cal2)) {
        System.out.println("Date1 is before Date2");
    }

    if (cal1.equals(cal2)) {
        System.out.println("Date1 is equal Date2");
    }
}

From source file:Main.java

public static void main(String[] args) {
    Date date1 = new Date(2009, 01, 10);
    Date date2 = new Date(2015, 07, 01);
    Calendar calendar1 = Calendar.getInstance();
    Calendar calendar2 = Calendar.getInstance();
    calendar1.setTime(date1);
    calendar2.setTime(date2);/*w w w .ja va 2  s .co  m*/
    long milliseconds1 = calendar1.getTimeInMillis();
    long milliseconds2 = calendar2.getTimeInMillis();
    long diff = milliseconds2 - milliseconds1;
    long diffSeconds = diff / 1000;
    long diffMinutes = diff / (60 * 1000);
    long diffHours = diff / (60 * 60 * 1000);
    long diffDays = diff / (24 * 60 * 60 * 1000);
    System.out.println("\nThe Date Different Example");
    System.out.println("Time in milliseconds: " + diff + " milliseconds.");
    System.out.println("Time in seconds: " + diffSeconds + " seconds.");
    System.out.println("Time in minutes: " + diffMinutes + " minutes.");
    System.out.println("Time in hours: " + diffHours + " hours.");
    System.out.println("Time in days: " + diffDays + " days.");
}

From source file:com.glaf.core.job.SysDataLogCreateTableJob.java

public static void main(String[] args) {
    Date date = DateUtils.getDateAfter(new Date(), 0);
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    int year = calendar.get(Calendar.YEAR);
    int month = calendar.get(Calendar.MONTH);
    int daysOfMonth = DateUtils.getYearMonthDays(year, month + 1);

    calendar.set(year, month, daysOfMonth);

    int begin = getYearMonthDay(date);
    int end = getYearMonthDay(calendar.getTime());

    for (int i = begin; i <= end; i++) {
        logger.debug(i);/*from w w  w  .ja va  2  s .co m*/
        try {
            SysDataLogTableUtils.createTable("SYS_DATA_LOG_" + i);
        } catch (Exception ex) {
            ex.printStackTrace();
            logger.error(ex);
        }
    }

}

From source file:Main.java

public static void main(String[] args) {

    Calendar cal = Calendar.getInstance();

    // get the current time
    System.out.println("Current time is :" + cal.getTime());

    Date date = new Date();
    cal.setTime(date);

    // print the new time
    System.out.println("After setting Time:  " + cal.getTime());
}

From source file:Main.java

public static void main(String[] args) throws ParseException {
    SimpleDateFormat dateFormat = new SimpleDateFormat("ddMMyyyy");
    Calendar cal = Calendar.getInstance();
    String today = dateFormat.format(cal.getTime());
    System.out.println(today);/*from   ww  w.j a v a2s.  co  m*/

    SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyy");
    Date actualdate = sdf.parse(today);
    Date date1 = sdf.parse("20042014");
    Date date2 = sdf.parse("23042015");
    Calendar actual = Calendar.getInstance();
    Calendar cal1 = Calendar.getInstance();
    Calendar cal2 = Calendar.getInstance();
    actual.setTime(actualdate);
    cal1.setTime(date1);
    cal2.setTime(date2);

    System.out.println(actual);
    System.out.println(cal1);
    System.out.println(cal2);

    if (actualdate.after(date1) && actualdate.before(date2)) {
        System.out.println("Yes");
    } else {
        System.out.println("No");
    }

    if (actual.after(cal1) && actual.before(cal2)) {
        System.out.println("Yes");
    } else {
        System.out.println("No");
    }

}

From source file:fr.itinerennes.bundler.integration.onebusaway.GenerateStaticObaApiResults.java

public static void main(String[] args) throws IOException, GtfsException {

    final String url = args[0];
    final String key = args[1];
    final String gtfsFile = args[2];
    final String out = args[3].replaceAll("/$", "");

    final Map<String, String> agencyMapping = new HashMap<String, String>();
    agencyMapping.put("1", "2");
    final GtfsDao gtfs = GtfsUtils.load(new File(gtfsFile), agencyMapping);

    oba = new JsonOneBusAwayClient(new DefaultHttpClient(), url, key);
    gson = OneBusAwayGsonFactory.newInstance(true);

    final Calendar end = Calendar.getInstance();
    end.set(2013, 11, 22, 0, 0);/*from   ww  w . j  a  v a2  s  .  c o  m*/

    final Calendar start = Calendar.getInstance();
    start.set(2013, 10, 4, 0, 0);

    final Calendar current = Calendar.getInstance();
    current.setTime(start.getTime());

    while (current.before(end) || current.equals(end)) {
        System.out.println(current.getTime());
        for (final Stop stop : gtfs.getAllStops()) {
            final String stopId = stop.getId().toString();
            final String dateDir = String.format("%04d/%02d/%02d", current.get(Calendar.YEAR),
                    current.get(Calendar.MONTH) + 1, current.get(Calendar.DAY_OF_MONTH));
            final String methodDir = String.format("%s/schedule-for-stop", out);

            final File outDir = new File(String.format("%s/%s", methodDir, dateDir));
            outDir.mkdirs();
            final File f = new File(outDir, String.format("%s.json", stopId));

            final StopSchedule ss = oba.getScheduleForStop(stopId, current.getTime());
            final String json = gson.toJson(ss);

            final Writer w = new PrintWriter(f);
            w.write(json);
            w.close();
        }
        current.add(Calendar.DAY_OF_MONTH, 1);
    }

    final File outDir = new File(String.format("%s/trip-details", out));
    outDir.mkdirs();
    for (final Trip trip : gtfs.getAllTrips()) {
        final String tripId = trip.getId().toString();
        final File f = new File(outDir, String.format("%s.json", tripId));

        final TripSchedule ts = oba.getTripDetails(tripId);
        final String json = gson.toJson(ts);

        final Writer w = new PrintWriter(f);
        w.write(json);
        w.close();
    }
}

From source file:com.dc.gameserver.extComponents.Kit.DateUtil.java

public static void main(String args[]) throws ParseException {
    //Date date1 = new Date(playerDailyTaskModel.getCreateTime().getTime());
    Calendar cal1 = Calendar.getInstance();
    Calendar cal2 = Calendar.getInstance();
    cal1.setTime(new Date(Timestamp.valueOf("2012-04-15 20:00:00").getTime()));
    cal2.setTime(new Date(Timestamp.valueOf("2012-04-16 12:00:00").getTime()));
    System.out.println("cal1.WEEK_OF_YEAR=:" + cal1.get(Calendar.WEEK_OF_YEAR));
    System.out.println("cal2.WEEK_OF_YEAR=:" + cal2.get(Calendar.WEEK_OF_YEAR));

}

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

public static void main(String[] args) {
    initializeLogStore();/*w w w  .  jav a  2 s . c  om*/

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

public static void main(String[] args) {
    try {/*from w  w  w  .j  a  v a 2 s  . co  m*/

        Calendar start = Calendar.getInstance();

        start.set(1899, 11, 30, 0, 0);

        PicasawebService myService = new PicasawebService("My Application");
        myService.setUserCredentials(args[0], args[1]);

        // Get a list of all entries
        URL metafeedUrl = new URL("http://picasaweb.google.com/data/feed/api/user/" + args[0] + "?kind=album");
        System.out.println("Getting Picasa Web Albums entries...\n");
        UserFeed resultFeed = myService.getFeed(metafeedUrl, UserFeed.class);

        // resultFeed.

        File root = new File(args[2]);
        File[] albuns = root.listFiles();

        int j = 0;
        List<GphotoEntry> entries = resultFeed.getEntries();
        for (int i = 0; i < entries.size(); i++) {
            GphotoEntry entry = entries.get(i);
            String href = entry.getHtmlLink().getHref();

            String name = entry.getTitle().getPlainText();

            for (File album : albuns) {
                if (album.getName().equals(name) && !href.contains("02?")) {
                    File picasaini = new File(album, "Picasa.ini");

                    if (!picasaini.exists()) {
                        StringBuilder builder = new StringBuilder();

                        builder.append("\n");
                        builder.append("[Picasa]\n");
                        builder.append("name=");
                        builder.append(name);
                        builder.append("\n");
                        builder.append("location=");
                        Collection<Extension> extensions = entry.getExtensions();

                        for (Extension extension : extensions) {

                            if (extension instanceof GphotoLocation) {
                                GphotoLocation location = (GphotoLocation) extension;
                                if (location.getValue() != null) {
                                    builder.append(location.getValue());
                                }
                            }
                        }
                        builder.append("\n");
                        builder.append("category=Folders on Disk");
                        builder.append("\n");
                        builder.append("date=");
                        String source = name.substring(0, 10);

                        DateFormat formater = new SimpleDateFormat("yyyy-MM-dd");

                        Date date = formater.parse(source);

                        Calendar end = Calendar.getInstance();

                        end.setTime(date);

                        builder.append(daysBetween(start, end));
                        builder.append(".000000");
                        builder.append("\n");
                        builder.append(args[0]);
                        builder.append("_lh=");
                        builder.append(entry.getGphotoId());
                        builder.append("\n");
                        builder.append("P2category=Folders on Disk");
                        builder.append("\n");

                        URL feedUrl = new URL("https://picasaweb.google.com/data/feed/api/user/" + args[0]
                                + "/albumid/" + entry.getGphotoId());

                        AlbumFeed feed = myService.getFeed(feedUrl, AlbumFeed.class);

                        for (GphotoEntry photo : feed.getEntries()) {
                            builder.append("\n");
                            builder.append("[");
                            builder.append(photo.getTitle().getPlainText());
                            builder.append("]");
                            builder.append("\n");
                            long id = Long.parseLong(photo.getGphotoId());

                            builder.append("IIDLIST_");
                            builder.append(args[0]);
                            builder.append("_lh=");
                            builder.append(Long.toHexString(id));
                            builder.append("\n");
                        }

                        System.out.println(builder.toString());
                        IOUtils.write(builder.toString(), new FileOutputStream(picasaini));
                        j++;
                    }
                }

            }

        }
        System.out.println(j);
        System.out.println("\nTotal Entries: " + entries.size());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:io.druid.examples.rabbitmq.RabbitMQProducerMain.java

public static void main(String[] args) throws Exception {
    // We use a List to keep track of option insertion order. See below.
    final List<Option> optionList = new ArrayList<Option>();

    optionList.add(OptionBuilder.withLongOpt("help").withDescription("display this help message").create("h"));
    optionList.add(OptionBuilder.withLongOpt("hostname").hasArg()
            .withDescription("the hostname of the AMQP broker [defaults to AMQP library default]").create("b"));
    optionList.add(OptionBuilder.withLongOpt("port").hasArg()
            .withDescription("the port of the AMQP broker [defaults to AMQP library default]").create("n"));
    optionList.add(OptionBuilder.withLongOpt("username").hasArg()
            .withDescription("username to connect to the AMQP broker [defaults to AMQP library default]")
            .create("u"));
    optionList.add(OptionBuilder.withLongOpt("password").hasArg()
            .withDescription("password to connect to the AMQP broker [defaults to AMQP library default]")
            .create("p"));
    optionList.add(OptionBuilder.withLongOpt("vhost").hasArg()
            .withDescription("name of virtual host on the AMQP broker [defaults to AMQP library default]")
            .create("v"));
    optionList.add(OptionBuilder.withLongOpt("exchange").isRequired().hasArg()
            .withDescription("name of the AMQP exchange [required - no default]").create("e"));
    optionList.add(OptionBuilder.withLongOpt("key").hasArg()
            .withDescription("the routing key to use when sending messages [default: 'default.routing.key']")
            .create("k"));
    optionList.add(OptionBuilder.withLongOpt("type").hasArg()
            .withDescription("the type of exchange to create [default: 'topic']").create("t"));
    optionList.add(OptionBuilder.withLongOpt("durable")
            .withDescription("if set, a durable exchange will be declared [default: not set]").create("d"));
    optionList.add(OptionBuilder.withLongOpt("autodelete")
            .withDescription("if set, an auto-delete exchange will be declared [default: not set]")
            .create("a"));
    optionList.add(OptionBuilder.withLongOpt("single")
            .withDescription("if set, only a single message will be sent [default: not set]").create("s"));
    optionList.add(OptionBuilder.withLongOpt("start").hasArg()
            .withDescription("time to use to start sending messages from [default: 2010-01-01T00:00:00]")
            .create());//from   w  w w  . java 2  s.  c o  m
    optionList.add(OptionBuilder.withLongOpt("stop").hasArg().withDescription(
            "time to use to send messages until (format: '2013-07-18T23:45:59') [default: current time]")
            .create());
    optionList.add(OptionBuilder.withLongOpt("interval").hasArg()
            .withDescription("the interval to add to the timestamp between messages in seconds [default: 10]")
            .create());
    optionList.add(OptionBuilder.withLongOpt("delay").hasArg()
            .withDescription("the delay between sending messages in milliseconds [default: 100]").create());

    // An extremely silly hack to maintain the above order in the help formatting.
    HelpFormatter formatter = new HelpFormatter();
    // Add a comparator to the HelpFormatter using the ArrayList above to sort by insertion order.
    formatter.setOptionComparator(new Comparator() {
        @Override
        public int compare(Object o1, Object o2) {
            // I know this isn't fast, but who cares! The list is short.
            return optionList.indexOf(o1) - optionList.indexOf(o2);
        }
    });

    // Now we can add all the options to an Options instance. This is dumb!
    Options options = new Options();
    for (Option option : optionList) {
        options.addOption(option);
    }

    CommandLine cmd = null;

    try {
        cmd = new BasicParser().parse(options, args);

    } catch (ParseException e) {
        formatter.printHelp("RabbitMQProducerMain", e.getMessage(), options, null);
        System.exit(1);
    }

    if (cmd.hasOption("h")) {
        formatter.printHelp("RabbitMQProducerMain", options);
        System.exit(2);
    }

    ConnectionFactory factory = new ConnectionFactory();

    if (cmd.hasOption("b")) {
        factory.setHost(cmd.getOptionValue("b"));
    }
    if (cmd.hasOption("u")) {
        factory.setUsername(cmd.getOptionValue("u"));
    }
    if (cmd.hasOption("p")) {
        factory.setPassword(cmd.getOptionValue("p"));
    }
    if (cmd.hasOption("v")) {
        factory.setVirtualHost(cmd.getOptionValue("v"));
    }
    if (cmd.hasOption("n")) {
        factory.setPort(Integer.parseInt(cmd.getOptionValue("n")));
    }

    String exchange = cmd.getOptionValue("e");
    String routingKey = "default.routing.key";
    if (cmd.hasOption("k")) {
        routingKey = cmd.getOptionValue("k");
    }

    boolean durable = cmd.hasOption("d");
    boolean autoDelete = cmd.hasOption("a");
    String type = cmd.getOptionValue("t", "topic");
    boolean single = cmd.hasOption("single");
    int interval = Integer.parseInt(cmd.getOptionValue("interval", "10"));
    int delay = Integer.parseInt(cmd.getOptionValue("delay", "100"));

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    Date stop = sdf.parse(cmd.getOptionValue("stop", sdf.format(new Date())));

    Random r = new Random();
    Calendar timer = Calendar.getInstance();
    timer.setTime(sdf.parse(cmd.getOptionValue("start", "2010-01-01T00:00:00")));

    String msg_template = "{\"utcdt\": \"%s\", \"wp\": %d, \"gender\": \"%s\", \"age\": %d}";

    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.exchangeDeclare(exchange, type, durable, autoDelete, null);

    do {
        int wp = (10 + r.nextInt(90)) * 100;
        String gender = r.nextBoolean() ? "male" : "female";
        int age = 20 + r.nextInt(70);

        String line = String.format(msg_template, sdf.format(timer.getTime()), wp, gender, age);

        channel.basicPublish(exchange, routingKey, null, line.getBytes());

        System.out.println("Sent message: " + line);

        timer.add(Calendar.SECOND, interval);

        Thread.sleep(delay);
    } while ((!single && stop.after(timer.getTime())));

    connection.close();
}