Example usage for org.joda.time DateTime year

List of usage examples for org.joda.time DateTime year

Introduction

In this page you can find the example usage for org.joda.time DateTime year.

Prototype

public Property year() 

Source Link

Document

Get the year property which provides access to advanced functionality.

Usage

From source file:nl.basjes.parse.httpdlog.dissectors.TimeStampDissector.java

License:Apache License

@Override
public void dissect(final Parsable<?> parsable, final String inputname) throws DissectionFailure {
    final ParsedField field = parsable.getParsableField(INPUT_TYPE, inputname);
    String fieldValue = field.getValue().getString();
    if (fieldValue == null || fieldValue.isEmpty()) {
        return; // Nothing to do here
    }/*w  w  w. jav  a 2  s .  c  o  m*/

    fieldValue = fieldValue.toLowerCase(Locale.getDefault());

    if (wantAnyAsParsed || wantAnyTZIndependent) {
        // YUCK ! Parsing the same thing TWICE just for the Zone ?!?!?
        DateTime dateTime = asParsedFormatter.parseDateTime(fieldValue);
        DateTimeZone zone = dateTime.getZone();
        DateTimeFormatter asParsedWithZoneFormatter = asParsedFormatter.withZone(zone);
        dateTime = asParsedWithZoneFormatter.parseDateTime(fieldValue);

        // As parsed
        if (wantDay) {
            parsable.addDissection(inputname, "TIME.DAY", "day", dateTime.dayOfMonth().get());
        }
        if (wantMonthname) {
            parsable.addDissection(inputname, "TIME.MONTHNAME", "monthname",
                    dateTime.monthOfYear().getAsText(Locale.getDefault()));
        }
        if (wantMonth) {
            parsable.addDissection(inputname, "TIME.MONTH", "month", dateTime.monthOfYear().get());
        }
        if (wantWeekOfWeekYear) {
            parsable.addDissection(inputname, "TIME.WEEK", "weekofweekyear", dateTime.weekOfWeekyear().get());
        }
        if (wantWeekYear) {
            parsable.addDissection(inputname, "TIME.YEAR", "weekyear", dateTime.weekyear().get());
        }
        if (wantYear) {
            parsable.addDissection(inputname, "TIME.YEAR", "year", dateTime.year().get());
        }
        if (wantHour) {
            parsable.addDissection(inputname, "TIME.HOUR", "hour", dateTime.hourOfDay().get());
        }
        if (wantMinute) {
            parsable.addDissection(inputname, "TIME.MINUTE", "minute", dateTime.minuteOfHour().get());
        }
        if (wantSecond) {
            parsable.addDissection(inputname, "TIME.SECOND", "second", dateTime.secondOfMinute().get());
        }
        if (wantMillisecond) {
            parsable.addDissection(inputname, "TIME.MILLISECOND", "millisecond",
                    dateTime.millisOfSecond().get());
        }
        if (wantDate) {
            parsable.addDissection(inputname, "TIME.DATE", "date", ISO_DATE_FORMATTER.print(dateTime));
        }

        if (wantTime) {
            parsable.addDissection(inputname, "TIME.TIME", "time", ISO_TIME_FORMATTER.print(dateTime));
        }

        // Timezone independent
        if (wantTimezone) {
            parsable.addDissection(inputname, "TIME.TIMEZONE", "timezone", dateTime.getZone().getID());
        }
        if (wantEpoch) {
            parsable.addDissection(inputname, "TIME.EPOCH", "epoch", dateTime.getMillis());
        }
    }

    if (wantAnyUTC) {
        // In UTC timezone
        DateTime dateTime = formatter.parseDateTime(fieldValue);

        if (wantDayUTC) {
            parsable.addDissection(inputname, "TIME.DAY", "day_utc", dateTime.dayOfMonth().get());
        }
        if (wantMonthnameUTC) {
            parsable.addDissection(inputname, "TIME.MONTHNAME", "monthname_utc",
                    dateTime.monthOfYear().getAsText(Locale.getDefault()));
        }
        if (wantMonthUTC) {
            parsable.addDissection(inputname, "TIME.MONTH", "month_utc", dateTime.monthOfYear().get());
        }
        if (wantWeekOfWeekYearUTC) {
            parsable.addDissection(inputname, "TIME.WEEK", "weekofweekyear_utc",
                    dateTime.weekOfWeekyear().get());
        }
        if (wantWeekYearUTC) {
            parsable.addDissection(inputname, "TIME.YEAR", "weekyear_utc", dateTime.weekyear().get());
        }
        if (wantYearUTC) {
            parsable.addDissection(inputname, "TIME.YEAR", "year_utc", dateTime.year().get());
        }
        if (wantHourUTC) {
            parsable.addDissection(inputname, "TIME.HOUR", "hour_utc", dateTime.hourOfDay().get());
        }
        if (wantMinuteUTC) {
            parsable.addDissection(inputname, "TIME.MINUTE", "minute_utc", dateTime.minuteOfHour().get());
        }
        if (wantSecondUTC) {
            parsable.addDissection(inputname, "TIME.SECOND", "second_utc", dateTime.secondOfMinute().get());
        }
        if (wantMillisecondUTC) {
            parsable.addDissection(inputname, "TIME.MILLISECOND", "millisecond_utc",
                    dateTime.millisOfSecond().get());
        }
        if (wantDateUTC) {
            parsable.addDissection(inputname, "TIME.DATE", "date_utc", ISO_DATE_FORMATTER.print(dateTime));
        }

        if (wantTimeUTC) {
            parsable.addDissection(inputname, "TIME.TIME", "time_utc", ISO_TIME_FORMATTER.print(dateTime));
        }

    }
}

From source file:org.apache.druid.query.expression.TimestampExtractExprMacro.java

License:Apache License

@Override
public Expr apply(final List<Expr> args) {
    if (args.size() < 2 || args.size() > 3) {
        throw new IAE("Function[%s] must have 2 to 3 arguments", name());
    }/*from   ww  w .  j a  v a 2  s  .  c  o  m*/

    if (!args.get(1).isLiteral() || args.get(1).getLiteralValue() == null) {
        throw new IAE("Function[%s] unit arg must be literal", name());
    }

    if (args.size() > 2 && !args.get(2).isLiteral()) {
        throw new IAE("Function[%s] timezone arg must be literal", name());
    }

    final Expr arg = args.get(0);
    final Unit unit = Unit.valueOf(StringUtils.toUpperCase((String) args.get(1).getLiteralValue()));
    final DateTimeZone timeZone;

    if (args.size() > 2) {
        timeZone = ExprUtils.toTimeZone(args.get(2));
    } else {
        timeZone = DateTimeZone.UTC;
    }

    final ISOChronology chronology = ISOChronology.getInstance(timeZone);

    class TimestampExtractExpr extends ExprMacroTable.BaseScalarUnivariateMacroFunctionExpr {
        private TimestampExtractExpr(Expr arg) {
            super(arg);
        }

        @Nonnull
        @Override
        public ExprEval eval(final ObjectBinding bindings) {
            Object val = arg.eval(bindings).value();
            if (val == null) {
                // Return null if the argument if null.
                return ExprEval.of(null);
            }
            final DateTime dateTime = new DateTime(val, chronology);
            long epoch = dateTime.getMillis() / 1000;

            switch (unit) {
            case EPOCH:
                return ExprEval.of(epoch);
            case MICROSECOND:
                return ExprEval.of(epoch / 1000);
            case MILLISECOND:
                return ExprEval.of(dateTime.millisOfSecond().get());
            case SECOND:
                return ExprEval.of(dateTime.secondOfMinute().get());
            case MINUTE:
                return ExprEval.of(dateTime.minuteOfHour().get());
            case HOUR:
                return ExprEval.of(dateTime.hourOfDay().get());
            case DAY:
                return ExprEval.of(dateTime.dayOfMonth().get());
            case DOW:
                return ExprEval.of(dateTime.dayOfWeek().get());
            case ISODOW:
                return ExprEval.of(dateTime.dayOfWeek().get());
            case DOY:
                return ExprEval.of(dateTime.dayOfYear().get());
            case WEEK:
                return ExprEval.of(dateTime.weekOfWeekyear().get());
            case MONTH:
                return ExprEval.of(dateTime.monthOfYear().get());
            case QUARTER:
                return ExprEval.of((dateTime.monthOfYear().get() - 1) / 3 + 1);
            case YEAR:
                return ExprEval.of(dateTime.year().get());
            case ISOYEAR:
                return ExprEval.of(dateTime.year().get());
            case DECADE:
                // The year field divided by 10, See https://www.postgresql.org/docs/10/functions-datetime.html
                return ExprEval.of(Math.floor(dateTime.year().get() / 10));
            case CENTURY:
                return ExprEval.of(dateTime.centuryOfEra().get() + 1);
            case MILLENNIUM:
                // Years in the 1900s are in the second millennium. The third millennium started January 1, 2001.
                // See https://www.postgresql.org/docs/10/functions-datetime.html
                return ExprEval.of(Math.round(Math.ceil(dateTime.year().get() / 1000)));
            default:
                throw new ISE("Unhandled unit[%s]", unit);
            }
        }

        @Override
        public Expr visit(Shuttle shuttle) {
            Expr newArg = arg.visit(shuttle);
            return shuttle.visit(new TimestampExtractExpr(newArg));
        }
    }

    return new TimestampExtractExpr(arg);
}

From source file:org.apache.fineract.accounting.closure.storeglaccountbalance.service.GLClosureJournalEntryBalanceReadPlatformServiceImpl.java

License:Apache License

/**
 * Create the csv file with the balance report data
 *
 * @param reportDataList/*from  www .ja  v a 2 s . c  o m*/
 * @return {@link File} object
 */
private File createGLClosureAccountBalanceReportGreatPlainsFile(
        final Collection<GLClosureAccountBalanceReportData> reportDataList) {
    File file = null;

    try {
        final String fileDirectory = FileSystemContentRepository.MIFOSX_BASE_DIR + File.separator + "";

        if (!new File(fileDirectory).isDirectory()) {
            new File(fileDirectory).mkdirs();
        }

        DateTime dateTime = DateTime.now();
        String year = dateTime.year().getAsString();
        String month = String.format("%02d", dateTime.monthOfYear().get());
        String day = String.format("%02d", dateTime.dayOfMonth().get());
        String hour = String.format("%02d", dateTime.hourOfDay().get());
        String minute = String.format("%02d", dateTime.minuteOfHour().get());
        String second = String.format("%02d", dateTime.secondOfMinute().get());

        file = new File(
                fileDirectory + "JRNL_" + year + month + day + hour + minute + second + "_001" + ".txt");

        // use FileWriter constructor that specifies open for appending

        FileWriter fileWriter = new FileWriter(file);

        for (GLClosureAccountBalanceReportData reportData : reportDataList) {
            final LinkedHashMap<String, String> fields = new LinkedHashMap<>();
            fields.put("companyId", this.configurationDomainService.getCompanyId());
            fields.put("batchNumber",
                    "GLPOS" + year.substring(year.length() - 2) + month + day + hour + minute);
            fields.put("reference", "");
            fields.put("transactionDate", "");
            fields.put("transactionType", "0"); //transactionType (0 = regular, 1 = reversing) is always 0
            fields.put("transactionId", "");
            fields.put("series", "2"); // Always Financial (1=All; 2=Financial; 3=Sales; 4=Purchasing; 5=Inventory; 6=Payroll; 7=Project;)
            fields.put("currencyId", "");
            fields.put("exchangeRate", "");
            fields.put("rateTypeId", "");
            fields.put("expirationDate", "");
            fields.put("exchangeDate", "");
            fields.put("exchangeId", "");
            fields.put("exchangeRateSource", "");
            fields.put("rateExpiration", "0"); // no rate expiration (0=None; 1=Daily; 2=Weekly; 3=Bi-weekly; 4=Semiweekly; 5=Monthly; 6=Quarterly; 7=Annually; 8=Misc.; 9=None;)
            fields.put("transactionTime", "");
            fields.put("userId", "");
            fields.put("creditAmount", "");
            fields.put("debitAmount", "");
            fields.put("accountNoString", "");
            fields.put("description", "");
            fields.put("originatingControlNo", "");
            fields.put("originatingDocNo", "");
            fields.put("originatingMasterId", "");
            fields.put("originatingMasterName", "");
            fields.put("originatingTransationType", "");
            fields.put("originatingSequenceNo", "");
            fields.put("originatingTransactionDescription", "");
            fields.put("taxDetailId", "");
            fields.put("taxAmount", "");
            fields.put("taxAccount", "");

            if (reportData.getTransactionDate() != null) {
                String transactionDate = year + month + day;
                fields.put("transactionDate", transactionDate);
            }

            if (reportData.getAmount() != null) {
                String goodsAmount = reportData.getAmount().abs().setScale(2, RoundingMode.CEILING)
                        .toPlainString();
                if (reportData.getAmount().compareTo(BigDecimal.ZERO) < 0) {
                    fields.put("creditAmount", goodsAmount);
                } else {
                    fields.put("debitAmount", goodsAmount);
                }
            }

            if (reportData.getReference() != null) {
                String reference = reportData.getReference();
                fields.put("reference", reference);
                fields.put("description", reference);
            }

            if (reportData.getAccountNumber() != null) {
                fields.put("accountNoString", reportData.getAccountNumber());
            }

            if (reportData.getClosureId() != null) {
                fields.put("transactionId", reportData.getClosureId().toString());
            }

            for (String key : fields.keySet()) {
                fileWriter.write(fields.get(key) + "|");
            }

            fileWriter.write(System.lineSeparator());
        }

        fileWriter.close();
    }

    catch (Exception exception) {
        logger.error(exception.getMessage(), exception);
    }

    return file;
}

From source file:org.apache.phoenix.expression.function.CeilYearExpression.java

License:Apache License

@Override
public long roundDateTime(DateTime dateTime) {
    return dateTime.year().roundCeilingCopy().getMillis();
}

From source file:org.apache.phoenix.expression.function.FloorYearExpression.java

License:Apache License

@Override
public long roundDateTime(DateTime datetime) {
    return datetime.year().roundFloorCopy().getMillis();
}

From source file:org.apache.phoenix.expression.function.RoundYearExpression.java

License:Apache License

@Override
public long roundDateTime(DateTime dateTime) {
    return dateTime.year().roundHalfEvenCopy().getMillis();
}

From source file:org.epics.archiverappliance.common.TimeUtils.java

/**
 * Determine year from java epoch seconds.
 * @param epochseconds/*from   w  ww.j  a  va2 s .c om*/
 * @param startOfYearInSeconds
 * @return
 */
public static short computeYearForEpochSeconds(long epochseconds) {
    // The JODA DateTime constructor takes millis
    DateTime dateTime = new DateTime(epochseconds * 1000, DateTimeZone.UTC);
    return (short) dateTime.year().get();
}

From source file:org.epics.archiverappliance.common.TimeUtils.java

/**
 * Get the current year in the UTC timezone
 * @return//from   w w w .j  a v  a  2  s .  co  m
 */
public static short getCurrentYear() {
    DateTime dateTime = new DateTime(DateTimeZone.UTC);
    return (short) dateTime.year().get();
}

From source file:org.jevis.commons.driver.DataSourceHelper.java

License:Open Source License

private static DateTime getFolderTime(String name, String[] pathStream) {
    String compactDateString = getCompactDateString(name, pathStream);
    String compactDataFormatString = getCompactDateFormatString(name, pathStream);

    DateTimeFormatter dtf = DateTimeFormat.forPattern(compactDataFormatString);

    DateTime parseDateTime = dtf.parseDateTime(compactDateString);
    if (parseDateTime.year().get() == parseDateTime.year().getMinimumValue()) {
        parseDateTime = parseDateTime.year().withMaximumValue();
    }//from  w  ww .j a  v  a 2s.  c o  m
    if (parseDateTime.monthOfYear().get() == parseDateTime.monthOfYear().getMinimumValue()) {
        parseDateTime = parseDateTime.monthOfYear().withMaximumValue();
    }
    if (parseDateTime.dayOfMonth().get() == parseDateTime.dayOfMonth().getMinimumValue()) {
        parseDateTime = parseDateTime.dayOfMonth().withMaximumValue();
    }
    if (parseDateTime.hourOfDay().get() == parseDateTime.hourOfDay().getMinimumValue()) {
        parseDateTime = parseDateTime.hourOfDay().withMaximumValue();
    }
    if (parseDateTime.minuteOfHour().get() == parseDateTime.minuteOfHour().getMinimumValue()) {
        parseDateTime = parseDateTime.minuteOfHour().withMaximumValue();
    }
    if (parseDateTime.secondOfMinute().get() == parseDateTime.secondOfMinute().getMinimumValue()) {
        parseDateTime = parseDateTime.secondOfMinute().withMaximumValue();
    }
    if (parseDateTime.millisOfSecond().get() == parseDateTime.millisOfSecond().getMinimumValue()) {
        parseDateTime = parseDateTime.millisOfSecond().withMaximumValue();
    }
    return parseDateTime;
}

From source file:org.joda.example.time.DateTimePerformance.java

License:Apache License

private void checkJodaSetGetYear() {
    int COUNT = COUNT_FAST;
    // Is it fair to use only MutableDateTime here? You decide.
    //        MutableDateTime dt = new MutableDateTime(GJChronology.getInstance());
    //        for (int i = 0; i < AVERAGE; i++) {
    //            start("Joda", "setGetYear");
    //            for (int j = 0; j < COUNT; j++) {
    //                dt.setYear(1972);
    //                int val = dt.getYear();
    //                if (val < 0) {System.out.println("Anti optimise");}
    //            }
    //            end(COUNT);
    //        }/*from w  w w .  j a v a 2 s  .  c o  m*/
    DateTime dt = new DateTime(GJChronology.getInstance());
    for (int i = 0; i < AVERAGE; i++) {
        start("Joda", "setGetYear");
        for (int j = 0; j < COUNT; j++) {
            dt = dt.year().setCopy(1972);
            int val = dt.getYear();
            if (val < 0) {
                System.out.println("Anti optimise");
            }
        }
        end(COUNT);
    }
}