Example usage for org.joda.time DateTime withYear

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

Introduction

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

Prototype

public DateTime withYear(int year) 

Source Link

Document

Returns a copy of this datetime with the year field updated.

Usage

From source file:DataRequestParser.java

private DateTime getDateWith(int year, int doy) {

    // temp date object
    DateTime dt = new DateTime();

    // set the year
    dt = dt.withYear(year);

    // set the day of year
    dt = dt.withDayOfYear(doy);/*from ww  w . j a  va  2 s .  c  o  m*/

    return dt;

}

From source file:com.hurence.logisland.util.time.DateUtil.java

License:Apache License

/**
 * Validate the actual date of the given date string based on the given date format pattern and
 * return a date instance based on the given date string.
 * @param dateString The date string./* ww  w.  j a v a2 s.c o m*/
 * @param dateFormat The date format pattern which should respect the SimpleDateFormat rules.
 * @param timeZone The timezone to use to parse the date.
 * @return The parsed date object.
 * @throws ParseException If the given date string or its actual date is invalid based on the
 * given date format pattern.
 * @see SimpleDateFormat
 */
public static Date parse(String dateString, String dateFormat, TimeZone timeZone) throws ParseException {
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat, new Locale("en", "US"));
    simpleDateFormat.setTimeZone(timeZone);
    simpleDateFormat.setLenient(false); // Don't automatically convert invalid date.
    if (dateFormat.equals("MMM dd HH:mm:ss")) {

        DateTime today = new DateTime();
        DateTime parsedDate = new DateTime(simpleDateFormat.parse(dateString));

        DateTime parsedDateWithTodaysYear = parsedDate.withYear(today.getYear());

        return parsedDateWithTodaysYear.toDate();
    } else {
        return simpleDateFormat.parse(dateString);
    }
}

From source file:com.kopysoft.chronos.activities.fragment.JobFragment.java

License:Open Source License

@Override
public void onPause() {
    super.onPause();

    Chronos chrono = new Chronos(getActivity());
    Job thisJob = chrono.getAllJobs().get(0);
    /*/* w  w  w. j  a  v a 2  s.  co  m*/
    EditText dataPayRate;
    Spinner dataPayPeriodLength;
    DatePicker dataStartOfPayPeriod;
    TimePicker dataTimePicker;
    */

    Log.d(TAG, "onPause()");

    dataPayRate.clearFocus();
    dataPayPeriodLength.clearFocus();
    dataStartOfPayPeriod.clearFocus();
    dataTimePicker.clearFocus();

    try {
        thisJob.setPayRate(Float.parseFloat(dataPayRate.getText().toString()));
        Log.d(TAG, "Pay Rate: " + thisJob.getPayRate());
    } catch (NumberFormatException e) {
        Toast.makeText(getActivity(), "Pay Rate format incorrect", Toast.LENGTH_SHORT).show();
    }

    PayPeriodDuration duration = PayPeriodDuration.values()[dataPayPeriodLength.getSelectedItemPosition()];
    thisJob.setDuration(duration);

    DateTime newTime = thisJob.getStartOfPayPeriod();
    newTime = newTime.withDayOfMonth(dataStartOfPayPeriod.getDayOfMonth());
    newTime = newTime.withMonthOfYear(dataStartOfPayPeriod.getMonth() + 1);
    newTime = newTime.withYear(dataStartOfPayPeriod.getYear());

    newTime = newTime.withHourOfDay(dataTimePicker.getCurrentHour());
    newTime = newTime.withMinuteOfHour(dataTimePicker.getCurrentMinute());

    thisJob.setStartOfPayPeriod(newTime);
    chrono.updateJob(thisJob);
    chrono.close();
}

From source file:com.mastfrog.acteur.headers.DateTimeHeader.java

License:Open Source License

@Override
public DateTime toValue(String value) {
    long val = 0;
    if (val == 0) {
        try {/*from w  w w  . j a v a 2  s . c  o m*/
            val = Headers.ISO2822DateFormat.parseDateTime(value).getMillis();
        } catch (IllegalArgumentException e) {
            try {
                //Sigh...use java.util.date to handle "GMT", "PST", "EST"
                val = Date.parse(value);
            } catch (IllegalArgumentException ex) {
                new IllegalArgumentException(value, ex).printStackTrace();
                return null;
            }
        }
    }
    DateTime result = new DateTime(val, DateTimeZone.UTC);
    //to be truly compliant, accept 2-digit dates
    if (result.getYear() < 100 && result.getYear() > 0) {
        if (result.getYear() >= 50) {
            result = result.withYear(2000 - (100 - result.getYear())).withDayOfYear(result.getDayOfYear() - 1); //don't ask
        } else {
            result = result.withYear(2000 + result.getYear());
        }
    }
    return result;
}

From source file:com.streamsets.pipeline.lib.parser.syslog.SyslogParser.java

License:Apache License

/**
 * Parse the RFC3164 date format. This is trickier than it sounds because this
 * format does not specify a year so we get weird edge cases at year
 * boundaries. This implementation tries to "do what I mean".
 * @param ts RFC3164-compatible timestamp to be parsed
 * @return Typical (for Java) milliseconds since the UNIX epoch
 *///from   www.j  av  a2 s . co  m
protected long parseRfc3164Time(String ts) throws OnRecordErrorException {
    DateTime now = DateTime.now();
    int year = now.getYear();
    ts = TWO_SPACES.matcher(ts).replaceFirst(" ");
    DateTime date;
    try {
        date = rfc3164Format.parseDateTime(ts);
    } catch (IllegalArgumentException e) {
        throw new OnRecordErrorException(Errors.SYSLOG_10, ts, e);
    }
    // try to deal with boundary cases, i.e. new year's eve.
    // rfc3164 dates are really dumb.
    // NB: cannot handle replaying of old logs or going back to the future
    DateTime fixed = date.withYear(year);
    // flume clock is ahead or there is some latency, and the year rolled
    if (fixed.isAfter(now) && fixed.minusMonths(1).isAfter(now)) {
        fixed = date.withYear(year - 1);
        // flume clock is behind and the year rolled
    } else if (fixed.isBefore(now) && fixed.plusMonths(1).isBefore(now)) {
        fixed = date.withYear(year + 1);
    }
    date = fixed;
    return date.getMillis();
}

From source file:com.streamsets.pipeline.lib.parser.udp.syslog.SyslogParser.java

License:Apache License

/**
 * Parse the RFC3164 date format. This is trickier than it sounds because this
 * format does not specify a year so we get weird edge cases at year
 * boundaries. This implementation tries to "do what I mean".
 * @param ts RFC3164-compatible timestamp to be parsed
 * @return Typical (for Java) milliseconds since the UNIX epoch
 *///from w w  w.j  av a 2 s  . c  o m
protected long parseRfc3164Time(String recordIdentifer, String msg, String ts) throws OnRecordErrorException {
    DateTime now = DateTime.now();
    int year = now.getYear();
    ts = TWO_SPACES.matcher(ts).replaceFirst(" ");
    DateTime date;
    try {
        date = rfc3164Format.parseDateTime(ts);
    } catch (IllegalArgumentException e) {
        throw throwOnRecordErrorException(recordIdentifer, msg, Errors.SYSLOG_10, ts, e);
    }
    // try to deal with boundary cases, i.e. new year's eve.
    // rfc3164 dates are really dumb.
    // NB: cannot handle replaying of old logs or going back to the future
    DateTime fixed = date.withYear(year);
    // flume clock is ahead or there is some latency, and the year rolled
    if (fixed.isAfter(now) && fixed.minusMonths(1).isAfter(now)) {
        fixed = date.withYear(year - 1);
        // flume clock is behind and the year rolled
    } else if (fixed.isBefore(now) && fixed.plusMonths(1).isBefore(now)) {
        fixed = date.withYear(year + 1);
    }
    date = fixed;
    return date.getMillis();
}

From source file:dk.dma.epd.common.prototype.model.voct.SARISXMLParser.java

License:Apache License

private SARWeatherData getSingleSARWeatherData(Node node) throws XPathExpressionException {

    Element el = (Element) node;
    NodeList children = el.getChildNodes();
    Node timeEntry = children.item(1);

    Element timeElement = (Element) timeEntry;

    NodeList timeNodes = timeElement.getChildNodes();

    DateTime windEntryDate = new DateTime();

    // Day 0//from  w  ww .j  a  va 2  s  .c o m
    windEntryDate = windEntryDate
            .withDayOfMonth(Integer.parseInt(timeNodes.item(0).getFirstChild().getNodeValue()));

    // Month 2
    windEntryDate = windEntryDate
            .withMonthOfYear(Integer.parseInt(timeNodes.item(2).getFirstChild().getNodeValue()));

    // Year 4
    windEntryDate = windEntryDate.withYear(Integer.parseInt(timeNodes.item(4).getFirstChild().getNodeValue()));

    // hour 6
    windEntryDate = windEntryDate
            .withHourOfDay(Integer.parseInt(timeNodes.item(6).getFirstChild().getNodeValue()));

    // minute 8
    windEntryDate = windEntryDate
            .withMinuteOfHour(Integer.parseInt(timeNodes.item(8).getFirstChild().getNodeValue()));

    // second 10
    windEntryDate = windEntryDate
            .withSecondOfMinute(Integer.parseInt(timeNodes.item(10).getFirstChild().getNodeValue()));

    Node windEntry = children.item(3);
    Element windElements = (Element) windEntry;
    NodeList windNodes = windElements.getChildNodes();

    System.out.println(windElements.getFirstChild().getNodeValue());

    for (int k = 0; k < windNodes.getLength(); k++) {
        System.out.println("k is " + k);
        Node child2 = windNodes.item(k);
        System.out.println("Child2 name is " + child2.getNodeName());
        if (child2.getNodeType() != Node.TEXT_NODE) {
            System.out.println("child tag: " + child2.getNodeName());
            if (child2.getFirstChild().getNodeType() == Node.TEXT_NODE) {
                System.out.println("inner child value:" + child2.getFirstChild().getNodeValue());
            }

        }
    }

    // System.out.println(node.getChildNodes());

    // Get time
    // System.out.println(getDateFromNodeList(node.getChildNodes().item(1).getChildNodes()));
    // System.out.println(node.getChildNodes().item(1).getChildNodes().item(0).getChildNodes().item(0).getNodeValue());

    // Wind values
    // System.out.println(node.getChildNodes().item(3));

    // for (int i = 0; i < node.getChildNodes().getLength(); i++) {
    // System.out.println(node.getChildNodes().item(i).getChildNodes().item(1));
    // }

    return null;
}

From source file:dk.dma.epd.common.prototype.model.voct.SARISXMLParser.java

License:Apache License

private DateTime getDateFromNodeList(NodeList nodeList) {
    DateTime returnDate = new DateTime();

    if (nodeList.getLength() == 0) {
        return null;
    }//from   ww  w.jav a  2  s . c om

    if (nodeList.item(0).getNodeName().equals("day")) {
        // Day
        returnDate = returnDate
                .withDayOfMonth(Integer.parseInt(nodeList.item(0).getFirstChild().getNodeValue()));
        // System.out.println("DAY");
    }

    if (nodeList.item(1).getNodeName().equals("month")) {
        // Month
        returnDate = returnDate
                .withMonthOfYear(Integer.parseInt(nodeList.item(1).getFirstChild().getNodeValue()));
        // System.out.println("MONTH");
    }

    if (nodeList.item(2).getNodeName().equals("year")) {
        // Year
        returnDate = returnDate.withYear(Integer.parseInt(nodeList.item(2).getFirstChild().getNodeValue()));
        // System.out.println("YEAR");
    }

    if (nodeList.item(3).getNodeName().equals("hour")) {
        // Hour
        returnDate = returnDate
                .withHourOfDay(Integer.parseInt(nodeList.item(3).getFirstChild().getNodeValue()));
        // System.out.println("HOUR");
    }

    if (nodeList.item(4).getNodeName().equals("minute")) {
        // Minute
        returnDate = returnDate
                .withMinuteOfHour(Integer.parseInt(nodeList.item(4).getFirstChild().getNodeValue()));
        // System.out.println("MINUTE");
    }

    if (nodeList.item(5).getNodeName().equals("second")) {
        // Second
        returnDate = returnDate
                .withSecondOfMinute(Integer.parseInt(nodeList.item(5).getFirstChild().getNodeValue()));
        // System.out.println("SECOND");
    }

    return returnDate;

}

From source file:edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo.DateTimeWithPrecisionVTwo.java

License:Open Source License

private Map<String, String> checkDate(String precisionURI, Map<String, String[]> qp) {
    if (precisionURI == null)
        return Collections.emptyMap();

    Map<String, String> errors = new HashMap<String, String>();

    Integer year, month, day, hour, minute, second;

    //just check if the values for the precision parse to integers
    if (precisionURI.equals(VitroVocabulary.Precision.YEAR.uri())) {
        if (!canParseToNumber(getFieldName() + "-year", qp))
            errors.put(getFieldName() + "-year", NON_INTEGER_YEAR);
    } else if (precisionURI.equals(VitroVocabulary.Precision.MONTH.uri())) {
        if (!canParseToNumber(getFieldName() + "-year", qp))
            errors.put(getFieldName() + "-year", NON_INTEGER_YEAR);
        if (!canParseToNumber(getFieldName() + "-month", qp))
            errors.put(getFieldName() + "-month", NON_INTEGER_MONTH);
    } else if (precisionURI.equals(VitroVocabulary.Precision.DAY.uri())) {
        if (!canParseToNumber(getFieldName() + "-year", qp))
            errors.put(getFieldName() + "-year", NON_INTEGER_YEAR);
        if (!canParseToNumber(getFieldName() + "-month", qp))
            errors.put(getFieldName() + "-month", NON_INTEGER_MONTH);
        if (!canParseToNumber(getFieldName() + "-day", qp))
            errors.put(getFieldName() + "-day", NON_INTEGER_DAY);
    } else if (precisionURI.equals(VitroVocabulary.Precision.HOUR.uri())) {
        if (!canParseToNumber(getFieldName() + "-year", qp))
            errors.put(getFieldName() + "-year", NON_INTEGER_YEAR);
        if (!canParseToNumber(getFieldName() + "-month", qp))
            errors.put(getFieldName() + "-month", NON_INTEGER_MONTH);
        if (!canParseToNumber(getFieldName() + "-day", qp))
            errors.put(getFieldName() + "-day", NON_INTEGER_DAY);
        if (!canParseToNumber(getFieldName() + "-hour", qp))
            errors.put(getFieldName() + "-hour", NON_INTEGER_HOUR);
    } else if (precisionURI.equals(VitroVocabulary.Precision.MINUTE.uri())) {
        if (!canParseToNumber(getFieldName() + "-year", qp))
            errors.put(getFieldName() + "-year", NON_INTEGER_YEAR);
        if (!canParseToNumber(getFieldName() + "-month", qp))
            errors.put(getFieldName() + "-month", NON_INTEGER_MONTH);
        if (!canParseToNumber(getFieldName() + "-day", qp))
            errors.put(getFieldName() + "-day", NON_INTEGER_DAY);
        if (!canParseToNumber(getFieldName() + "-hour", qp))
            errors.put(getFieldName() + "-hour", NON_INTEGER_HOUR);
        if (!canParseToNumber(getFieldName() + "-minute", qp))
            errors.put(getFieldName() + "-minute", NON_INTEGER_HOUR);
    } else if (precisionURI.equals(VitroVocabulary.Precision.SECOND.uri())) {
        if (!canParseToNumber(getFieldName() + "-year", qp))
            errors.put(getFieldName() + "-year", NON_INTEGER_YEAR);
        if (!canParseToNumber(getFieldName() + "-month", qp))
            errors.put(getFieldName() + "-month", NON_INTEGER_MONTH);
        if (!canParseToNumber(getFieldName() + "-day", qp))
            errors.put(getFieldName() + "-day", NON_INTEGER_DAY);
        if (!canParseToNumber(getFieldName() + "-hour", qp))
            errors.put(getFieldName() + "-hour", NON_INTEGER_HOUR);
        if (!canParseToNumber(getFieldName() + "-minute", qp))
            errors.put(getFieldName() + "-minute", NON_INTEGER_HOUR);
        if (!canParseToNumber(getFieldName() + "-second", qp))
            errors.put(getFieldName() + "-second", NON_INTEGER_SECOND);
    }/*from  w w  w.  j av a2 s .c  om*/

    //check if we can make a valid date with these integers
    year = parseToInt(getFieldName() + "-year", qp);
    if (year == null)
        year = 1999;
    month = parseToInt(getFieldName() + "-month", qp);
    if (month == null)
        month = 1;
    day = parseToInt(getFieldName() + "-day", qp);
    if (day == null)
        day = 1;
    hour = parseToInt(getFieldName() + "-hour", qp);
    if (hour == null)
        hour = 0;
    minute = parseToInt(getFieldName() + "-minute", qp);
    if (minute == null)
        minute = 0;
    second = parseToInt(getFieldName() + "-second", qp);
    if (second == null)
        second = 0;

    //initialize to something so that we can be assured not to get 
    //system date dependent behavior
    DateTime dateTime = new DateTime("1970-01-01T00:00:00Z");

    try {
        dateTime = dateTime.withYear(year);
    } catch (IllegalArgumentException iae) {
        errors.put(getFieldName() + "-year", iae.getLocalizedMessage());
    }
    try {
        dateTime = dateTime.withMonthOfYear(month);
    } catch (IllegalArgumentException iae) {
        errors.put(getFieldName() + "-month", iae.getLocalizedMessage());
    }
    try {
        dateTime = dateTime.withDayOfMonth(day);
    } catch (IllegalArgumentException iae) {
        errors.put(getFieldName() + "-day", iae.getLocalizedMessage());
    }
    try {
        dateTime = dateTime.withHourOfDay(hour);
    } catch (IllegalArgumentException iae) {
        errors.put(getFieldName() + "-hour", iae.getLocalizedMessage());
    }
    try {
        dateTime = dateTime.withSecondOfMinute(second);
    } catch (IllegalArgumentException iae) {
        errors.put(getFieldName() + "-second", iae.getLocalizedMessage());
    }

    return errors;
}

From source file:net.tourbook.ui.views.tourCatalog.YearStatisticView.java

License:Open Source License

/**
 * get data for each displayed year//w  ww.  ja  va2 s .  c  o  m
 */
private void setYearData() {

    _displayedYears = new int[_numberOfYears];
    _numberOfDaysInYear = new int[_numberOfYears];

    final int firstYear = getFirstYear();

    final DateTime dt = (new DateTime()).withYear(firstYear).withWeekOfWeekyear(1)
            .withDayOfWeek(DateTimeConstants.MONDAY);

    int yearIndex = 0;
    for (int currentYear = firstYear; currentYear <= _lastYear; currentYear++) {

        _displayedYears[yearIndex] = currentYear;
        _numberOfDaysInYear[yearIndex] = dt.withYear(currentYear).dayOfYear().getMaximumValue();

        yearIndex++;
    }
}