Example usage for java.util Calendar DAY_OF_YEAR

List of usage examples for java.util Calendar DAY_OF_YEAR

Introduction

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

Prototype

int DAY_OF_YEAR

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

Click Source Link

Document

Field number for get and set indicating the day number within the current year.

Usage

From source file:cn.com.sinosoft.util.time.DurationFormatUtils.java

/**
 * <p>Formats the time gap as a string, using the specified format.
 * Padding the left hand side of numbers with zeroes is optional and 
 * the timezone may be specified. </p>
 *
 * <p>When calculating the difference between months/days, it chooses to 
 * calculate months first. So when working out the number of months and 
 * days between January 15th and March 10th, it choose 1 month and 
 * 23 days gained by choosing January->February = 1 month and then 
 * calculating days forwards, and not the 1 month and 26 days gained by 
 * choosing March -> February = 1 month and then calculating days 
 * backwards. </p>//from ww  w. j  a v  a2 s  . c o  m
 *
 * <p>For more control, the <a href="http://joda-time.sf.net/">Joda-Time</a>
 * library is recommended.</p>
 * 
 * @param startMillis  the start of the duration
 * @param endMillis  the end of the duration
 * @param format  the way in which to format the duration
 * @param padWithZeros whether to pad the left hand side of numbers with 0's
 * @param timezone the millis are defined in
 * @return the time as a String
 */
public static String formatPeriod(long startMillis, long endMillis, String format, boolean padWithZeros,
        TimeZone timezone) {

    // Used to optimise for differences under 28 days and 
    // called formatDuration(millis, format); however this did not work 
    // over leap years. 
    // TODO: Compare performance to see if anything was lost by 
    // losing this optimisation. 

    Token[] tokens = lexx(format);

    // timezones get funky around 0, so normalizing everything to GMT 
    // stops the hours being off
    Calendar start = Calendar.getInstance(timezone);
    start.setTime(new Date(startMillis));
    Calendar end = Calendar.getInstance(timezone);
    end.setTime(new Date(endMillis));

    // initial estimates
    int milliseconds = end.get(Calendar.MILLISECOND) - start.get(Calendar.MILLISECOND);
    int seconds = end.get(Calendar.SECOND) - start.get(Calendar.SECOND);
    int minutes = end.get(Calendar.MINUTE) - start.get(Calendar.MINUTE);
    int hours = end.get(Calendar.HOUR_OF_DAY) - start.get(Calendar.HOUR_OF_DAY);
    int days = end.get(Calendar.DAY_OF_MONTH) - start.get(Calendar.DAY_OF_MONTH);
    int months = end.get(Calendar.MONTH) - start.get(Calendar.MONTH);
    int years = end.get(Calendar.YEAR) - start.get(Calendar.YEAR);

    // each initial estimate is adjusted in case it is under 0
    while (milliseconds < 0) {
        milliseconds += 1000;
        seconds -= 1;
    }
    while (seconds < 0) {
        seconds += 60;
        minutes -= 1;
    }
    while (minutes < 0) {
        minutes += 60;
        hours -= 1;
    }
    while (hours < 0) {
        hours += 24;
        days -= 1;
    }

    if (Token.containsTokenWithValue(tokens, M)) {
        while (days < 0) {
            days += start.getActualMaximum(Calendar.DAY_OF_MONTH);
            months -= 1;
            start.add(Calendar.MONTH, 1);
        }

        while (months < 0) {
            months += 12;
            years -= 1;
        }

        if (!Token.containsTokenWithValue(tokens, y) && years != 0) {
            while (years != 0) {
                months += 12 * years;
                years = 0;
            }
        }
    } else {
        // there are no M's in the format string

        if (!Token.containsTokenWithValue(tokens, y)) {
            int target = end.get(Calendar.YEAR);
            if (months < 0) {
                // target is end-year -1
                target -= 1;
            }

            while ((start.get(Calendar.YEAR) != target)) {
                days += start.getActualMaximum(Calendar.DAY_OF_YEAR) - start.get(Calendar.DAY_OF_YEAR);

                // Not sure I grok why this is needed, but the brutal tests show it is
                if (start instanceof GregorianCalendar) {
                    if ((start.get(Calendar.MONTH) == Calendar.FEBRUARY)
                            && (start.get(Calendar.DAY_OF_MONTH) == 29)) {
                        days += 1;
                    }
                }

                start.add(Calendar.YEAR, 1);

                days += start.get(Calendar.DAY_OF_YEAR);
            }

            years = 0;
        }

        while (start.get(Calendar.MONTH) != end.get(Calendar.MONTH)) {
            days += start.getActualMaximum(Calendar.DAY_OF_MONTH);
            start.add(Calendar.MONTH, 1);
        }

        months = 0;

        while (days < 0) {
            days += start.getActualMaximum(Calendar.DAY_OF_MONTH);
            months -= 1;
            start.add(Calendar.MONTH, 1);
        }

    }

    // The rest of this code adds in values that 
    // aren't requested. This allows the user to ask for the 
    // number of months and get the real count and not just 0->11.

    if (!Token.containsTokenWithValue(tokens, d)) {
        hours += 24 * days;
        days = 0;
    }
    if (!Token.containsTokenWithValue(tokens, H)) {
        minutes += 60 * hours;
        hours = 0;
    }
    if (!Token.containsTokenWithValue(tokens, m)) {
        seconds += 60 * minutes;
        minutes = 0;
    }
    if (!Token.containsTokenWithValue(tokens, s)) {
        milliseconds += 1000 * seconds;
        seconds = 0;
    }

    return format(tokens, years, months, days, hours, minutes, seconds, milliseconds, padWithZeros);
}

From source file:gov.nih.nci.firebird.service.signing.DigitalSigningHelper.java

private X509V3CertificateGenerator buildX509V3CertificateGenerator(PublicKey publicKey, X509Certificate caCert,
        DigitalSigningDistinguishedName distinguishedName, long serialNumber, int validDays)
        throws CertificateEncodingException, CertificateParsingException {

    X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();

    // Calculate Expiration Date
    Calendar notBeforeCal = Calendar.getInstance();
    Date notBeforeDate = notBeforeCal.getTime();
    Calendar notAfterCal = Calendar.getInstance();
    notAfterCal.add(Calendar.DAY_OF_YEAR, validDays);
    Date notAfterDate = notAfterCal.getTime();

    ///* w w w.  j a v  a2 s  .  c o  m*/
    // create the certificate - version 3
    //
    v3CertGen.reset();

    v3CertGen.setSerialNumber(BigInteger.valueOf(serialNumber));
    v3CertGen.setIssuerDN(PrincipalUtil.getSubjectX509Principal(caCert));
    v3CertGen.setNotBefore(notBeforeDate);
    v3CertGen.setNotAfter(notAfterDate);
    v3CertGen.setSubjectDN(new X509Principal(getAttributeOrder(), buildAttributes(distinguishedName)));
    v3CertGen.setPublicKey(publicKey);
    v3CertGen.setSignatureAlgorithm("SHA256WithRSAEncryption");

    //
    // extensions
    //
    v3CertGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            new SubjectKeyIdentifierStructure(publicKey));

    v3CertGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            new AuthorityKeyIdentifierStructure(caCert));

    v3CertGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(0));

    return v3CertGen;
}

From source file:asl.util.PlotMaker.java

public void plotCoherence(double per[], double[] gamma, String plotString) {

    final String plotTitle = String.format("%04d%03d.%s.%s-%s", date.get(Calendar.YEAR),
            date.get(Calendar.DAY_OF_YEAR), station, channelX, channelY);
    final String pngName = String.format("%s/%04d%03d.%s.%s-%s.%s.png", outputDir, date.get(Calendar.YEAR),
            date.get(Calendar.DAY_OF_YEAR), station, channelX, channelY, plotString);

    File outputFile = new File(pngName);

    // Check that we will be able to output the file without problems and if not --> return
    if (!checkFileOut(outputFile)) {
        System.out.format("== plotCoherence: request to output plot=[%s] but we are unable to create it "
                + " --> skip plot\n", pngName);
        return;/*w  w  w  . ja  v  a2  s . c  om*/
    }

    final String legend = String.format("%s--%s", channelX, channelY);
    final XYSeries series1 = new XYSeries(legend);

    for (int k = 0; k < gamma.length; k++) {
        series1.add(per[k], gamma[k]);
    }

    //final XYItemRenderer renderer1 = new StandardXYItemRenderer();
    final XYLineAndShapeRenderer renderer1 = new XYLineAndShapeRenderer();
    Rectangle rectangle = new Rectangle(3, 3);
    renderer1.setSeriesShape(0, rectangle);
    renderer1.setSeriesShapesVisible(0, true);
    renderer1.setSeriesLinesVisible(0, false);

    Paint[] paints = new Paint[] { Color.red, Color.black };
    renderer1.setSeriesPaint(0, paints[0]);

    final NumberAxis rangeAxis1 = new NumberAxis("Coherence, Gamma");
    rangeAxis1.setRange(new Range(0, 1.2));
    rangeAxis1.setTickUnit(new NumberTickUnit(0.1));

    final LogarithmicAxis horizontalAxis = new LogarithmicAxis("Period (sec)");
    horizontalAxis.setRange(new Range(0.05, 10000));

    final XYSeriesCollection seriesCollection = new XYSeriesCollection();
    seriesCollection.addSeries(series1);

    final XYPlot xyplot = new XYPlot((XYDataset) seriesCollection, horizontalAxis, rangeAxis1, renderer1);

    xyplot.setDomainGridlinesVisible(true);
    xyplot.setRangeGridlinesVisible(true);
    xyplot.setRangeGridlinePaint(Color.black);
    xyplot.setDomainGridlinePaint(Color.black);

    final JFreeChart chart = new JFreeChart(xyplot);
    chart.setTitle(new TextTitle(plotTitle));

    try {
        ChartUtilities.saveChartAsPNG(outputFile, chart, 500, 300);
    } catch (IOException e) {
        System.err.println("Problem occurred creating chart.");

    }
}

From source file:edu.ucsb.nceas.metacattest.UploadIPCCDataTest.java

private String generateId() {
    int version = 1;
    StringBuffer docid = new StringBuffer(DATAIDPREFIX);
    docid.append(DOT);/*from   ww w . jav  a 2  s .  c o  m*/

    // Create a calendar to get the date formatted properly
    String[] ids = TimeZone.getAvailableIDs(-8 * 60 * 60 * 1000);
    SimpleTimeZone pdt = new SimpleTimeZone(-8 * 60 * 60 * 1000, ids[0]);
    pdt.setStartRule(Calendar.APRIL, 1, Calendar.SUNDAY, 2 * 60 * 60 * 1000);
    pdt.setEndRule(Calendar.OCTOBER, -1, Calendar.SUNDAY, 2 * 60 * 60 * 1000);
    Calendar calendar = new GregorianCalendar(pdt);
    Date trialTime = new Date();
    calendar.setTime(trialTime);

    int time = 0;

    docid.append(calendar.get(Calendar.YEAR));

    time = calendar.get(Calendar.DAY_OF_YEAR);
    if (time < 10) {
        docid.append("0");
        docid.append("0");
        docid.append(time);
    } else if (time < 100) {
        docid.append("0");
        docid.append(time);
    } else {
        docid.append(time);
    }

    time = calendar.get(Calendar.HOUR_OF_DAY);
    if (time < 10) {
        docid.append("0");
        docid.append(time);
    } else {
        docid.append(time);
    }

    time = calendar.get(Calendar.MINUTE);
    if (time < 10) {
        docid.append("0");
        docid.append(time);
    } else {
        docid.append(time);
    }

    time = calendar.get(Calendar.SECOND);
    if (time < 10) {
        docid.append("0");
        docid.append(time);
    } else {
        docid.append(time);
    }
    //sometimes this number is not unique, so we append a random number
    int random = (new Double(Math.random() * 100)).intValue();
    docid.append(random);
    docid.append(DOT);
    docid.append(version);

    return docid.toString();

}

From source file:controllers.core.TimesheetController.java

/**
 * Copy the entries (without "hours") of the previous report to the given
 * report (for a weekly)./*from   w  w  w .ja  v  a2 s  . c o m*/
 * 
 * @param reportId
 *            the report id
 */
@Restrict({ @Group(IMafConstants.TIMESHEET_ENTRY_PERMISSION) })
public Result weeklyCopy(Long reportId) {

    // get the report
    TimesheetReport report = TimesheetDao.getTimesheetReportById(reportId);

    // get the previous report
    TimesheetReport previousReport = TimesheetDao.getTimesheetReportByActorAndStartDate(report.actor.id,
            report.getPreviousStartDate());

    if (previousReport != null && previousReport.timesheetEntries != null
            && previousReport.timesheetEntries.size() > 0) {
        for (TimesheetEntry previousEntry : previousReport.timesheetEntries) {

            Ebean.beginTransaction();
            try {

                TimesheetEntry entry = new TimesheetEntry();
                entry.timesheetReport = report;
                entry.portfolioEntry = previousEntry.portfolioEntry;
                entry.portfolioEntryPlanningPackage = previousEntry.portfolioEntryPlanningPackage;
                entry.timesheetActivity = previousEntry.timesheetActivity;
                entry.save();

                for (int i = 0; i < 7; i++) {

                    TimesheetLog log = new TimesheetLog();
                    log.hours = 0.0;
                    log.timesheetEntry = entry;

                    Calendar cal = Calendar.getInstance();
                    cal.setTime(report.startDate);
                    cal.add(Calendar.DAY_OF_YEAR, i);
                    log.logDate = cal.getTime();

                    log.save();
                }

                Ebean.commitTransaction();

            } catch (Exception e) {
                Ebean.rollbackTransaction();
                return ControllersUtils.logAndReturnUnexpectedError(e, log, getConfiguration(),
                        getI18nMessagesPlugin());
            }
        }
        Utilities.sendSuccessFlashMessage(Msg.get("core.timesheet.fill.weekly.copy.successful"));
    } else {
        Utilities.sendInfoFlashMessage(Msg.get("core.timesheet.fill.weekly.copy.info.empty"));
    }

    // create the date format
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    return redirect(controllers.core.routes.TimesheetController.weeklyFill(sdf.format(report.startDate)));
}

From source file:com.haulmont.cuba.gui.upload.FileUploading.java

@Override
public void clearTempDirectory() {
    try {//from   w  w w  .j  av  a  2 s .c  o m
        File dir = new File(tempDir);
        File[] files = dir.listFiles();
        if (files == null)
            throw new IllegalStateException("Not a directory: " + tempDir);
        Date currentDate = timeSource.currentTimestamp();
        for (File file : files) {
            Date fileDate = new Date(file.lastModified());
            Calendar calendar = new GregorianCalendar();
            calendar.setTime(fileDate);
            calendar.add(Calendar.DAY_OF_YEAR, 2);
            if (currentDate.compareTo(calendar.getTime()) > 0) {
                deleteFileLink(file.getAbsolutePath());
                if (!file.delete()) {
                    log.warn(String.format("Could not remove temp file %s", file.getName()));
                }
            }
        }
    } catch (Exception ex) {
        log.error(ex.getMessage(), ex);
    }
}

From source file:org.jrecruiter.service.impl.JobServiceImpl.java

/** {@inheritDoc} */
@Override/*  w  w w .  j  a  v  a 2 s .c  om*/
public void removeOldJobs(final @NotNull Integer days) {

    final Calendar cal = CalendarUtils.getCalendarWithoutTime();
    cal.add(Calendar.DAY_OF_YEAR, days.intValue() * -1);

    final List<Job> jobs = jobDao.getJobsByUpdateDate(cal);

    LOGGER.info("Found " + jobs.size() + " jobs that are eligible for removal.");

    if (!jobs.isEmpty()) {

        final long jobsCount = jobDao.getJobsCount();

        for (final Job job : jobs) {
            jobDao.remove(job.getId());
        }

        JobCountPerDay jobCountPerDay = jobCountPerDayDao.getByDate(new Date());

        if (jobCountPerDay == null) {
            jobCountPerDay = new JobCountPerDay();
            jobCountPerDay.setJobDate(new Date());

        }

        jobCountPerDay.setNumberOfJobsDeleted(Long.valueOf(jobs.size()));
        jobCountPerDay.setNumberOfJobsPosted(Long.valueOf(0));
        jobCountPerDay.setTotalNumberOfJobs(jobsCount - jobs.size());
        jobCountPerDay.setAutomaticallyCleaned(Boolean.TRUE);
        jobCountPerDayDao.save(jobCountPerDay);

    }

}

From source file:fr.paris.lutece.plugins.form.utils.FormUtils.java

/**
 * Compare two timestamp and return true if  they have the same times unit(Day,week,month)
 * @param  timestamp1 timestamp1/*from w  w  w  .  j  a va 2 s . co m*/
 * @param  timestamp2 timestamp2
 * @param strTimesUnit (day,week,month)
 * @return Compare two timestamp and return true if  they have the same times unit(Day,week,month)
 */
public static boolean sameDate(Timestamp timestamp1, Timestamp timestamp2, String strTimesUnit) {
    Calendar caldate1 = new GregorianCalendar();
    caldate1.setTime(timestamp1);

    Calendar caldate2 = new GregorianCalendar();
    caldate2.setTime(timestamp2);

    if (strTimesUnit.equals(CONSTANT_GROUP_BY_DAY)
            && (caldate1.get(Calendar.YEAR) == caldate2.get(Calendar.YEAR))
            && (caldate1.get(Calendar.DAY_OF_YEAR) == caldate2.get(Calendar.DAY_OF_YEAR))) {
        return true;
    } else if (strTimesUnit.equals(CONSTANT_GROUP_BY_WEEK)
            && (caldate1.get(Calendar.YEAR) == caldate2.get(Calendar.YEAR))
            && (caldate1.get(Calendar.WEEK_OF_YEAR) == caldate2.get(Calendar.WEEK_OF_YEAR))) {
        return true;
    } else if (strTimesUnit.equals(CONSTANT_GROUP_BY_MONTH)
            && (caldate1.get(Calendar.YEAR) == caldate2.get(Calendar.YEAR))
            && (caldate1.get(Calendar.MONTH) == caldate2.get(Calendar.MONTH))) {
        return true;
    }

    return false;
}

From source file:com.xunlei.util.DateUtils.java

/**
 * <p>/*from w  w  w .  j  ava2s .  c  o  m*/
 * Checks if two calendar objects are on the same hour.
 * </p>
 * <p>
 * 28 Mar 2002 13:45 and 28 Mar 2002 13:01 would return true. 28 Mar 2002 13:45 and 28 Mar 2002 14:45 would return false.
 * </p>
 * 
 * @param date1 the first date, not altered, not null
 * @param date2 the second date, not altered, not null
 * @return true if they represent the same day
 * @throws IllegalArgumentException if either date is <code>null</code>
 * @author Weapon Chung
 * @since 2011-4-2 10:48:50
 */
public static boolean isSameHour(Calendar cal1, Calendar cal2) {
    if (cal1 == null || cal2 == null) {
        throw new IllegalArgumentException("The date must not be null");
    }
    return (cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA)
            && cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR)
            && cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR)
            && cal1.get(Calendar.HOUR_OF_DAY) == cal2.get(Calendar.HOUR_OF_DAY));
}

From source file:com.quartz.AmazonQuartzJob.java

public void execute(JobExecutionContext context) throws JobExecutionException {
    String error = "No error";
    SimpleDateFormat out = new SimpleDateFormat("hh:mm a");
    System.out.println(":::>>>Amazon Job Time Check @ " + out.format(new Date()));

    settingsHM = TextFileReadWrite.readSettings(file);

    String onoff = settingsHM.get("onoff"), emails = settingsHM.get("emails"),
            lastUpdate = settingsHM.get("lastUpdate");
    ArrayList<String> time = new ArrayList(Arrays.asList(settingsHM.get("time").split(";")));

    if (emails == null) {
        emails = ";";
    }/*w ww .  j  a v a2  s .  c  o  m*/
    Date lastDate;
    try {
        lastDate = out1.parse(lastUpdate);
    } catch (ParseException ex) {
        GregorianCalendar now = new GregorianCalendar();
        now.set(Calendar.DAY_OF_YEAR, -1);
        lastDate = now.getTime();
    }

    String[] emailArr = emails.replace(";;", ";").replace(";", " ").trim().split(" ");
    if (onoff.equalsIgnoreCase("checked")) {
        for (String e : time) {
            Date dScheduled, dNow;
            try {
                dScheduled = out.parse(e);
                dNow = out.parse(out.format(new Date()));
                if (dScheduled.getTime() == dNow.getTime()) {
                    System.out.println("\t---> Amazon task launch");

                    XMLOrderConfirmationFeedBuilder.generateShipConfirmXML();

                    try {
                        this.submitFeed();
                    } catch (IOException ex) {
                        System.out.println("Error occured in submitFeed method");
                        error += "Cannot submit feed.";
                    }

                    try {
                        if (emails != null && emails.length() > 0) {
                            for (String recipient : emailArr) {
                                InternetAddress.parse(recipient);
                                if (recipient.indexOf("@") > 0 && recipient.indexOf(".") > 0) {
                                    String subject = "Auto notification from AMZ order update application server";
                                    String msg = "Scheduled Amazon orders update executed.\nError/s: " + error
                                            + "\n\n Update contents:\n\n"
                                            + XML.toJSONObject(TextFileReadWrite
                                                    .readFile(new File("AMZ_Orders_Tracking_Feed.xml"))[0])
                                                    .toString(3);
                                    Emailer.Send(AKC_Creds.ANH_EMAIL, AKC_Creds.ANH_EMAIL_PWD, recipient,
                                            subject, msg);
                                }
                            }
                        }
                        System.out.println("===[email notifications send]===");
                        writeUpdateTimestamp();
                    } catch (MessagingException ex) {
                        System.out.println(ex.getMessage());
                    }

                } else {
                    //System.out.println("\txxx> AMZ task time not match | Scheduled: " + out.format(dScheduled) + " Now: " + out.format(dNow));
                }
            } catch (ParseException ex) {
                //System.out.println(ex.getMessage());
                error += " Cannot create XML feed.";
            }
        }
    }

}