Example usage for java.util Calendar getTime

List of usage examples for java.util Calendar getTime

Introduction

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

Prototype

public final Date getTime() 

Source Link

Document

Returns a Date object representing this Calendar's time value (millisecond offset from the Epoch").

Usage

From source file:fitmon.Client.java

public static void main(String[] args) throws IOException, ClientProtocolException, NoSuchAlgorithmException,
        InvalidKeyException, SAXException, ParserConfigurationException {
    Food food = null;//from   w  w w . j  a va  2  s .c om
    DietAPI dApi = new DietAPI();
    JDBCConnection jdbcCon = new JDBCConnection();
    ArrayList<Food> foodItems = dApi.getFood();
    Scanner scan = new Scanner(System.in);
    Calendar currentDate = Calendar.getInstance(); //Get the current date
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd"); //format it as per your requirement
    String dateNow = formatter.format(currentDate.getTime());
    System.out.println("Now the date is :=>  " + dateNow);
    for (int i = 0; i < foodItems.size(); i++) {
        food = foodItems.get(i);
        System.out.println("ID : " + food.getFoodID());
        System.out.println("servingID : " + food.getServingID());
        System.out.println("Name : " + food.getItemName());
        System.out.println("category : " + food.getCategory());
        System.out.println("Quantity : " + food.getQuantity());
        System.out.println("calories : " + food.getCalories());
        System.out.println("fat : " + food.getFat());
        System.out.println("carbs : " + food.getCarbs());
        System.out.println("protein : " + food.getProtein());
        System.out.println("fiber : " + food.getFiber());
        System.out.println("sodium : " + food.getSodium());
        System.out.println("sugar : " + food.getSugar());
        System.out.println("cholesterol : " + food.getCholesterol());
        System.out.println(
                "------------------------------------------------------------------------------------------------");

    }

    System.out.println("Choose a meal......");
    String mealType = scan.next();
    System.out.println("Choose an item......");
    String servingID = scan.next();
    for (int j = 0; j < foodItems.size(); j++) {
        if (foodItems.get(j).getServingID() == null ? servingID == null
                : foodItems.get(j).getServingID().equals(servingID)) {
            food = foodItems.get(j);
            break;
        }

    }
    Diet diet = new CustomizedDiet();
    diet.createDiet(food, mealType, dateNow);

}

From source file:org.lieuofs.extraction.commune.mutation.ExtracteurMutation.java

public static void main(String[] args) throws IOException {
    ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "beans_extraction.xml" });
    ExtracteurMutation extracteur = (ExtracteurMutation) context.getBean("extracteurMutation");
    Calendar cal = Calendar.getInstance();
    cal.set(2013, Calendar.JANUARY, 1);
    BufferedWriter writer = new BufferedWriter(
            new OutputStreamWriter(new FileOutputStream("MutationCommune2013.txt"), "Windows-1252"));
    extracteur.extraireMutation(cal.getTime(), writer);
}

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

public static void main(String[] args) {
    initializeLogStore();/*from www  .j a v  a2  s  . co  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:Main.java

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

    // 15-04-2012
    calendar.set(Calendar.DAY_OF_MONTH, 15);
    calendar.set(Calendar.YEAR, 2012);
    calendar.set(Calendar.HOUR, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MONTH, 3);
    Date start = calendar.getTime();

    // 15-06-2012
    calendar.set(Calendar.MONTH, 5);
    Date end = calendar.getTime();

    calendar.setTime(start);// w w  w. j a  v a2s  .c o m
    Date d = null;
    while ((d = calendar.getTime()).before(end) || d.equals(end)) {
        int day = calendar.get(Calendar.DAY_OF_WEEK);
        if (day != Calendar.SATURDAY && day != Calendar.SUNDAY) {
            System.out.println(d);
        }
        calendar.add(Calendar.DAY_OF_MONTH, 1);
    }
}

From source file:Main.java

public static void main(String[] args) {
    Calendar cal = Calendar.getInstance();
    int day = cal.get(Calendar.DATE);
    int month = cal.get(Calendar.MONTH) + 1;
    int year = cal.get(Calendar.YEAR);
    int dow = cal.get(Calendar.DAY_OF_WEEK);
    int dom = cal.get(Calendar.DAY_OF_MONTH);
    int doy = cal.get(Calendar.DAY_OF_YEAR);

    System.out.println("Current Date: " + cal.getTime());
    System.out.println("Day: " + day);
    System.out.println("Month: " + month);
    System.out.println("Year: " + year);
    System.out.println("Day of Week: " + dow);
    System.out.println("Day of Month: " + dom);
    System.out.println("Day of Year: " + doy);
}

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. java 2s  .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:Test.java

public static void main(String[] args) {
    Calendar calendar = Calendar.getInstance();
    if (calendar.isWeekDateSupported()) {
        System.out.println("Number of weeks in this year: " + calendar.getWeeksInWeekYear());
        System.out.println("Current week number: " + calendar.get(Calendar.WEEK_OF_YEAR));
    }/* w ww  .ja  v a2  s .c o m*/

    calendar.setWeekDate(2012, 16, 3);
    System.out.println(
            DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG).format(calendar.getTime()));

}

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);//from w w  w .  ja  v a 2  s  .co  m
    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);
        try {
            SysDataLogTableUtils.createTable("SYS_DATA_LOG_" + i);
        } catch (Exception ex) {
            ex.printStackTrace();
            logger.error(ex);
        }
    }

}

From source file:com.acceleratedio.pac_n_zoom.UploadVideo.java

/**
 * Upload the user-selected video to the user's YouTube channel. The code
 * looks for the video in the application's project folder and uses OAuth
 * 2.0 to authorize the API request./*from w  ww .j a  v a2 s .co m*/
 *
 * @param args command line args (not used).
 */
public static void main(String[] args) {

    MakePostRequest get_video = new MakePostRequest();
    get_video.execute();

    // This OAuth 2.0 access scope allows an application to upload files
    // to the authenticated user's YouTube channel, but doesn't allow
    // other types of access.
    List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube.upload");

    String vidFileName = PickAnmActivity.fil_nams[position].replace('/', '?') + ".mp4";
    String httpAddrs = "http://www.pnzanimate.me/Droid/db_rd.php?";
    httpAddrs += vidFileName;

    try {
        // Authorize the request.
        Credential credential = Auth.authorize(scopes, "uploadvideo");

        // This object is used to make YouTube Data API requests.
        youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential)
                .setApplicationName("youtube-cmdline-uploadvideo-sample").build();

        System.out.println("Uploading: " + SAMPLE_VIDEO_FILENAME);

        // Add extra information to the video before uploading.
        Video videoObjectDefiningMetadata = new Video();

        // Set the video to be publicly visible. This is the default
        // setting. Other supporting settings are "unlisted" and "private."
        VideoStatus status = new VideoStatus();
        status.setPrivacyStatus("public");
        videoObjectDefiningMetadata.setStatus(status);

        // Most of the video's metadata is set on the VideoSnippet object.
        VideoSnippet snippet = new VideoSnippet();

        // This code uses a Calendar instance to create a unique name and
        // description for test purposes so that you can easily upload
        // multiple files. You should remove this code from your project
        // and use your own standard names instead.
        Calendar cal = Calendar.getInstance();
        snippet.setTitle("Test Upload via Java on " + cal.getTime());
        snippet.setDescription(
                "Video uploaded via YouTube Data API V3 using the Java library " + "on " + cal.getTime());

        // Set the keyword tags that you want to associate with the video.
        List<String> tags = new ArrayList<String>();
        tags.add("test");
        tags.add("example");
        tags.add("java");
        tags.add("YouTube Data API V3");
        tags.add("erase me");
        snippet.setTags(tags);

        // Add the completed snippet object to the video resource.
        videoObjectDefiningMetadata.setSnippet(snippet);

        InputStreamContent mediaContent = new InputStreamContent("mp4",
                UploadVideo.class.getResourceAsStream("/sample-video.mp4"));

        // Insert the video. The command sends three arguments. The first
        // specifies which information the API request is setting and which
        // information the API response should return. The second argument
        // is the video resource that contains metadata about the new video.
        // The third argument is the actual video content.
        YouTube.Videos.Insert videoInsert = youtube.videos().insert("snippet,statistics,status",
                videoObjectDefiningMetadata, mediaContent);

        // Set the upload type and add an event listener.
        MediaHttpUploader uploader = videoInsert.getMediaHttpUploader();

        // Indicate whether direct media upload is enabled. A value of
        // "True" indicates that direct media upload is enabled and that
        // the entire media content will be uploaded in a single request.
        // A value of "False," which is the default, indicates that the
        // request will use the resumable media upload protocol, which
        // supports the ability to resume an upload operation after a
        // network interruption or other transmission failure, saving
        // time and bandwidth in the event of network failures.
        uploader.setDirectUploadEnabled(false);

        MediaHttpUploaderProgressListener progressListener = new MediaHttpUploaderProgressListener() {
            public void progressChanged(MediaHttpUploader uploader) throws IOException {
                switch (uploader.getUploadState()) {
                case INITIATION_STARTED:
                    System.out.println("Initiation Started");
                    break;
                case INITIATION_COMPLETE:
                    System.out.println("Initiation Completed");
                    break;
                case MEDIA_IN_PROGRESS:
                    System.out.println("Upload in progress");
                    System.out.println("Upload percentage: " + uploader.getProgress());
                    break;
                case MEDIA_COMPLETE:
                    System.out.println("Upload Completed!");
                    break;
                case NOT_STARTED:
                    System.out.println("Upload Not Started!");
                    break;
                }
            }
        };
        uploader.setProgressListener(progressListener);

        // Call the API and upload the video.
        Video returnedVideo = videoInsert.execute();

        // Print data about the newly inserted video from the API response.
        System.out.println("\n================== Returned Video ==================\n");
        System.out.println("  - Id: " + returnedVideo.getId());
        System.out.println("  - Title: " + returnedVideo.getSnippet().getTitle());
        System.out.println("  - Tags: " + returnedVideo.getSnippet().getTags());
        System.out.println("  - Privacy Status: " + returnedVideo.getStatus().getPrivacyStatus());
        System.out.println("  - Video Count: " + returnedVideo.getStatistics().getViewCount());

    } catch (GoogleJsonResponseException e) {
        System.err.println("GoogleJsonResponseException code: " + e.getDetails().getCode() + " : "
                + e.getDetails().getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        System.err.println("IOException: " + e.getMessage());
        e.printStackTrace();
    } catch (Throwable t) {
        System.err.println("Throwable: " + t.getMessage());
        t.printStackTrace();
    }
}

From source file:Test.java

public static void main(String[] args) {
    Calendar calendar = Calendar.getInstance();
    calendar.setWeekDate(2012, 16, 3);//w w  w . j  a v a2 s . c o  m

    Builder builder = new Builder();
    builder.setLanguage("hy");
    builder.setScript("Latn");
    builder.setRegion("IT");
    builder.setVariant("arevela");

    Locale locale = builder.build();
    Locale.setDefault(locale);

    System.out.println(
            DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG).format(calendar.getTime()));
    System.out.println("" + locale.getDisplayLanguage());

    builder.setLanguage("zh");
    builder.setScript("Hans");
    builder.setRegion("CN");

    locale = builder.build();
    Locale.setDefault(locale);

    System.out.println(
            DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG).format(calendar.getTime()));
    System.out.println("" + locale.getDisplayLanguage());

}