Example usage for org.joda.time DateTime withZoneRetainFields

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

Introduction

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

Prototype

public DateTime withZoneRetainFields(DateTimeZone newZone) 

Source Link

Document

Returns a copy of this datetime with a different time zone, preserving the field values.

Usage

From source file:org.apache.beam.sdk.extensions.sql.zetasql.DateFunctions.java

License:Apache License

public DateTime date(DateTime ts, String timezone) {
    return ts.withZoneRetainFields(DateTimeZone.forTimeZone(TimeZone.getTimeZone(timezone)));
}

From source file:org.apache.drill.exec.store.bson.BsonRecordReader.java

License:Apache License

private void writeTimeStamp(int timestamp, final MapOrListWriterImpl writer, String fieldName, boolean isList) {
    DateTime dateTime = new DateTime(timestamp);
    TimeWriter t;/*from  www.  j  av  a 2 s .  c  om*/
    if (isList == false) {
        t = writer.map.time(fieldName);
    } else {
        t = writer.list.time();
    }
    t.writeTime((int) (dateTime.withZoneRetainFields(org.joda.time.DateTimeZone.UTC).getMillis()));
}

From source file:org.apache.drill.exec.store.bson.BsonRecordReader.java

License:Apache License

private void writeDateTime(long readDateTime, final MapOrListWriterImpl writer, String fieldName,
        boolean isList) {
    DateTime date = new DateTime(readDateTime);
    DateWriter dt;/*from w ww .j  av a2 s.  c o m*/
    if (isList == false) {
        dt = writer.map.date(fieldName);
    } else {
        dt = writer.list.date();
    }
    dt.writeDate(date.withZoneRetainFields(org.joda.time.DateTimeZone.UTC).getMillis());
}

From source file:org.apache.druid.sql.calcite.planner.Calcites.java

License:Apache License

/**
 * Calcite expects "DATE" types to be number of days from the epoch to the UTC date matching the local time fields.
 *
 * @param dateTime joda timestamp//from   www .j  a v a 2  s.  c  o m
 * @param timeZone session time zone
 *
 * @return Calcite style date
 */
public static int jodaToCalciteDate(final DateTime dateTime, final DateTimeZone timeZone) {
    final DateTime date = dateTime.withZone(timeZone).dayOfMonth().roundFloorCopy();
    return Days.daysBetween(DateTimes.EPOCH, date.withZoneRetainFields(DateTimeZone.UTC)).getDays();
}

From source file:org.apache.wicket.datetime.DateConverter.java

License:Apache License

/**
 * @see org.apache.wicket.util.convert.IConverter#convertToObject(java.lang.String,
 *      java.util.Locale)//from   ww w  .j  av a2s  .c om
 */
public Date convertToObject(String value, Locale locale) {
    if (Strings.isEmpty(value)) {
        return null;
    }

    DateTimeFormatter format = getFormat(locale);
    if (format == null) {
        throw new IllegalStateException("format must be not null");
    }

    if (applyTimeZoneDifference) {
        TimeZone zone = getClientTimeZone();
        DateTime dateTime = null;

        // set time zone for client
        format = format.withZone(getTimeZone());

        try {
            // parse date retaining the time of the submission
            dateTime = format.parseDateTime(value);
        } catch (RuntimeException e) {
            throw new ConversionException(e);
        }
        // apply the server time zone to the parsed value
        if (zone != null) {
            dateTime = dateTime.withZoneRetainFields(DateTimeZone.forTimeZone(zone));
        }

        return dateTime.toDate();
    } else {
        try {
            DateTime date = format.parseDateTime(value);
            return date.toDate();
        } catch (RuntimeException e) {
            throw new ConversionException(e);
        }
    }
}

From source file:org.everit.jira.core.impl.DateTimeServer.java

License:Apache License

/**
 * Simple instance generator. Create the userTimeZone based on the given milliseconds.
 *
 * @param systemTimeZoneInMillis/*from ww  w.j av a  2  s. c  om*/
 *          The user DateTime in millis.
 *
 * @return A new DateTimeServer object.
 */
public static DateTimeServer getInstanceBasedOnSystemTimeZone(final long systemTimeZoneInMillis) {
    DateTime systemTimeZoneFromMilis = new DateTime(systemTimeZoneInMillis);
    systemTimeZoneFromMilis = systemTimeZoneFromMilis.withZoneRetainFields(TimetrackerUtil.getSystemTimeZone());
    DateTimeServer dateTimeServer = new DateTimeServer();
    dateTimeServer.setSystemTimeZone(systemTimeZoneFromMilis);
    return dateTimeServer;
}

From source file:org.everit.jira.core.impl.DateTimeServer.java

License:Apache License

/**
 * Simple instance generator. Create the userTimeZone based on the given milliseconds.
 *
 * @param userTimeZoneInMillis/* w w w .j a va2 s.co m*/
 *          The user DateTime in millis.
 *
 * @return A new DateTimeServer object.
 */
public static DateTimeServer getInstanceBasedOnUserTimeZone(final long userTimeZoneInMillis) {
    DateTime userTimeZoneFromMillis = new DateTime(userTimeZoneInMillis, DateTimeZone.UTC);
    userTimeZoneFromMillis = userTimeZoneFromMillis
            .withZoneRetainFields(TimetrackerUtil.getLoggedUserTimeZone());
    DateTimeServer dateTimeServer = new DateTimeServer();
    dateTimeServer.setUserTimeZone(userTimeZoneFromMillis);
    return dateTimeServer;
}

From source file:org.jadira.usertype.dateandtime.joda.columnmapper.StringColumnDateTimeMapper.java

License:Apache License

@Override
public DateTime fromNonNullValue(String s) {

    DateTime parsedDateTime = DATE_TIME_FORMATTER.parseDateTime(s);
    DateTimeZone correctTimeZone = parsedDateTime.getZone();
    DateTime utcDateTime = parsedDateTime.withZoneRetainFields(DateTimeZone.UTC);
    DateTime correctedDateTime = utcDateTime.withZone(correctTimeZone);
    return correctedDateTime;
}

From source file:org.jadira.usertype.dateandtime.joda.columnmapper.StringColumnDateTimeMapper.java

License:Apache License

@Override
public String toNonNullValue(DateTime value) {

    DateTimeZone correctTimeZone = value.getZone();
    DateTime utcDateTime = value.withZone(DateTimeZone.UTC);
    DateTime utcDateTimeWithCorrectTimeZone = utcDateTime.withZoneRetainFields(correctTimeZone);
    String dateTimeAsString = DATE_TIME_FORMATTER.print(utcDateTimeWithCorrectTimeZone);
    return dateTimeAsString;
}

From source file:org.jruby.RubyTime.java

License:LGPL

private static RubyTime createTime(IRubyObject recv, IRubyObject[] args, boolean gmt, boolean utcOffset) {
    Ruby runtime = recv.getRuntime();//ww w.j a  v a  2s  . c  om
    int len = ARG_SIZE;
    boolean isDst = false;
    boolean setTzRelative = false;
    long nanos = 0;

    DateTimeZone dtz;
    if (gmt) {
        dtz = DateTimeZone.UTC;
    } else if (args.length == 10 && args[9] instanceof RubyString) {
        if (utcOffset) {
            dtz = getTimeZoneFromUtcOffset(runtime, args[9]);
            setTzRelative = true;
        } else {
            dtz = getTimeZoneFromString(runtime, args[9].toString());
        }
    } else if (args.length == 10 && args[9].respondsTo("to_int")) {
        IRubyObject offsetInt = args[9].callMethod(runtime.getCurrentContext(), "to_int");
        dtz = getTimeZone(runtime, ((RubyNumeric) offsetInt).getLongValue());
    } else {
        dtz = getLocalTimeZone(runtime);
    }

    if (args.length == 10) {
        if (args[8] instanceof RubyBoolean)
            isDst = args[8].isTrue();

        args = new IRubyObject[] { args[5], args[4], args[3], args[2], args[1], args[0], runtime.getNil() };
    } else {
        // MRI accepts additional wday argument which appears to be ignored.
        len = args.length;

        if (len < ARG_SIZE) {
            IRubyObject[] newArgs = new IRubyObject[ARG_SIZE];
            System.arraycopy(args, 0, newArgs, 0, args.length);
            for (int i = len; i < ARG_SIZE; i++) {
                newArgs[i] = runtime.getNil();
            }
            args = newArgs;
            len = ARG_SIZE;
        }
    }

    if (args[0] instanceof RubyString) {
        args[0] = RubyNumeric.str2inum(runtime, (RubyString) args[0], 10, false);
    }

    int year = (int) RubyNumeric.num2long(args[0]);
    int month = 1;

    if (len > 1) {
        if (!args[1].isNil()) {
            IRubyObject tmp = args[1].checkStringType();
            if (!tmp.isNil()) {
                String monthString = tmp.toString().toLowerCase();
                Integer monthInt = MONTHS_MAP.get(monthString);

                if (monthInt != null) {
                    month = monthInt;
                } else {
                    try {
                        month = Integer.parseInt(monthString);
                    } catch (NumberFormatException nfExcptn) {
                        throw runtime.newArgumentError("Argument out of range.");
                    }
                }
            } else {
                month = (int) RubyNumeric.num2long(args[1]);
            }
        }
        if (1 > month || month > 12) {
            throw runtime.newArgumentError("Argument out of range: for month: " + month);
        }
    }

    int[] int_args = { 1, 0, 0, 0, 0, 0 };

    for (int i = 0; int_args.length >= i + 2; i++) {
        if (!args[i + 2].isNil()) {
            if (!(args[i + 2] instanceof RubyNumeric)) {
                if (args[i + 2].respondsTo("to_int")) {
                    args[i + 2] = args[i + 2].callMethod(runtime.getCurrentContext(), "to_int");
                } else {
                    args[i + 2] = args[i + 2].callMethod(runtime.getCurrentContext(), "to_i");
                }
            }

            int_args[i] = RubyNumeric.num2int(args[i + 2]);
        }
    }

    // Validate the times
    // Complying with MRI behavior makes it a little bit complicated. Logic copied from:
    // https://github.com/ruby/ruby/blob/trunk/time.c#L2609
    if ((int_args[0] < 1 || int_args[0] > 31) || (int_args[1] < 0 || int_args[1] > 24)
            || (int_args[1] == 24 && (int_args[2] > 0 || int_args[3] > 0))
            || (int_args[2] < 0 || int_args[2] > 59) || (int_args[3] < 0 || int_args[3] > 60)) {
        throw runtime.newArgumentError("argument out of range.");
    }

    DateTime dt;
    // set up with min values and then add to allow rolling over
    try {
        dt = new DateTime(year, 1, 1, 0, 0, 0, 0, DateTimeZone.UTC);

        dt = dt.plusMonths(month - 1).plusDays(int_args[0] - 1).plusHours(int_args[1]).plusMinutes(int_args[2])
                .plusSeconds(int_args[3]);

        // 1.9 will observe fractional seconds *if* not given usec
        if (!args[5].isNil() && args[6].isNil()) {
            double secs = RubyFloat.num2dbl(args[5]);
            int int_millis = (int) (secs * 1000) % 1000;
            dt = dt.plusMillis(int_millis);
            nanos = ((long) (secs * 1000000000) % 1000000);
        }

        dt = dt.withZoneRetainFields(dtz);

        // If we're at a DST boundary, we need to choose the correct side of the boundary
        if (isDst) {
            final DateTime beforeDstBoundary = dt.withEarlierOffsetAtOverlap();
            final DateTime afterDstBoundary = dt.withLaterOffsetAtOverlap();

            final int offsetBeforeBoundary = dtz.getOffset(beforeDstBoundary);
            final int offsetAfterBoundary = dtz.getOffset(afterDstBoundary);

            // If the time is during DST, we need to pick the time with the highest offset
            dt = offsetBeforeBoundary > offsetAfterBoundary ? beforeDstBoundary : afterDstBoundary;
        }
    } catch (org.joda.time.IllegalFieldValueException e) {
        throw runtime.newArgumentError("time out of range");
    }

    RubyTime time = new RubyTime(runtime, (RubyClass) recv, dt);
    // Ignores usec if 8 args (for compatibility with parsedate) or if not supplied.
    if (args.length != 8 && !args[6].isNil()) {
        boolean fractionalUSecGiven = args[6] instanceof RubyFloat || args[6] instanceof RubyRational;

        if (fractionalUSecGiven) {
            double micros = RubyNumeric.num2dbl(args[6]);
            time.dt = dt.withMillis(dt.getMillis() + (long) (micros / 1000));
            nanos = ((long) (micros * 1000) % 1000000);
        } else {
            int usec = int_args[4] % 1000;
            int msec = int_args[4] / 1000;

            if (int_args[4] < 0) {
                msec -= 1;
                usec += 1000;
            }
            time.dt = dt.withMillis(dt.getMillis() + msec);
            time.setUSec(usec);
        }
    }

    if (nanos != 0)
        time.setNSec(nanos);

    time.callInit(IRubyObject.NULL_ARRAY, Block.NULL_BLOCK);
    time.setIsTzRelative(setTzRelative);
    return time;
}