@Override public java.sql.Timestamp getPrimitiveJavaObject(Object o) { if (o == null) { return null; } final NullableTimeStampHolder h = (NullableTimeStampHolder) o; org.joda.time.LocalDateTime dateTime = new org.joda.time.LocalDateTime(h.value, org.joda.time.DateTimeZone.UTC); // use "toDate()" to get java.util.Date object with exactly the same fields as this Joda date-time. // See more in Javadoc for "LocalDateTime#toDate()" return new java.sql.Timestamp(dateTime.toDate().getTime()); }
private DateTime parseDateTime(final String scheduleDate, final String scheduleTime) { // scheduleTime: 12,00,pm,PDT final String[] parts = scheduleTime.split(",", -1); int hour = Integer.parseInt(parts[0]); final int minutes = Integer.parseInt(parts[1]); final boolean isPm = parts[2].equalsIgnoreCase("pm"); final DateTimeZone timezone = parts[3].equals("UTC") ? DateTimeZone.UTC : DateTimeZone.getDefault(); // scheduleDate: 02/10/2013 DateTime day = null; if (scheduleDate == null || scheduleDate.trim().length() == 0) { day = new LocalDateTime().toDateTime(); } else { day = DateTimeFormat.forPattern("MM/dd/yyyy") .withZone(timezone).parseDateTime(scheduleDate); } hour %= 12; if (isPm) { hour += 12; } final DateTime firstSchedTime = day.withHourOfDay(hour).withMinuteOfHour(minutes).withSecondOfMinute(0); return firstSchedTime; }
private boolean isDatePatternHourly(String datePattern) { DateTimeFormatter formatter = DateTimeFormat.forPattern(datePattern); LocalDateTime refDateTime = new LocalDateTime(2017, 01, 01, 10, 0, 0); String refDateTimeString = refDateTime.toString(formatter); LocalDateTime refDateTimeAtStartOfDay = refDateTime.withHourOfDay(0); String refDateTimeStringAtStartOfDay = refDateTimeAtStartOfDay.toString(formatter); return !refDateTimeString.equals(refDateTimeStringAtStartOfDay); }
/** * Returns a copy of this datetime with different local millis. * <p> * The returned object will be a new instance of the same type. * Only the millis will change, the chronology is kept. * The returned object will be either be a new instance or <code>this</code>. * * @param newMillis the new millis, from 1970-01-01T00:00:00 * @return a copy of this datetime with different millis */ LocalDateTime withLocalMillis(long newMillis) { return (newMillis == getLocalMillis() ? this : new LocalDateTime(newMillis, getChronology())); }
/** * Converts this object to a DateTime using the specified zone. * <p> * When the time zone is applied, the local date-time may be affected by daylight saving. * In a daylight saving gap, when the local time does not exist, * this method will throw an exception. * In a daylight saving overlap, when the same local time occurs twice, * this method returns the first occurrence of the local time. * * @param zone time zone to apply, or default if null * @return a DateTime using the same millis * @throws IllegalInstantException if the local time does not exist when the time zone is applied */ public DateTime toDateTime(DateTimeZone zone) { zone = DateTimeUtils.getZone(zone); Chronology chrono = iChronology.withZone(zone); return new DateTime( getYear(), getMonthOfYear(), getDayOfMonth(), getHourOfDay(), getMinuteOfHour(), getSecondOfMinute(), getMillisOfSecond(), chrono); }
@Override public Timestamp convertToTimestamp(LocalDateTime t) { return new Timestamp(t.toDateTime().getMillis()); }
@Override public Timestamp toNonNullValue(LocalTime value) { DateTime zonedValue = new LocalDateTime( 1970,1,1,value.getHourOfDay(), value.getMinuteOfHour(), value.getSecondOfMinute(), value.getMillisOfSecond(), value.getChronology() ).toDateTime(); final Timestamp timestamp = new Timestamp(zonedValue.getMillis()); return timestamp; } }
LocalDate localDate; if (text.length() == 23) { LocalDateTime localDateTime = LocalDateTime.parse(text); localDate = localDateTime.toLocalDate(); } else { localDate = parseLocalDate(text, format, formatter); LocalTime localDate; if (text.length() == 23) { LocalDateTime localDateTime = LocalDateTime.parse(text); localDate = localDateTime.toLocalTime(); } else { localDate = LocalTime.parse(text); return (T) new DateTime(millis, DateTimeZone.forTimeZone(timeZone)); LocalDateTime localDateTime = new LocalDateTime(millis, DateTimeZone.forTimeZone(timeZone)); if (type == LocalDateTime.class) { return (T) localDateTime; return (T) localDateTime.toLocalDate(); return (T) localDateTime.toLocalTime();
private Object getRandomValueForTimeColumn(boolean isSimpleDate) { long randomMs = ThreadLocalRandom.current().nextLong(startTime); long dateColVal = randomMs; Object result; if (isSimpleDate) { DateTime dateTime = new DateTime(randomMs); LocalDateTime localDateTime = dateTime.toLocalDateTime(); int year = localDateTime.getYear(); int month = localDateTime.getMonthOfYear(); int day = localDateTime.getDayOfMonth(); String dateColStr = String.format("%04d%02d%02d", year, month, day); dateColVal = Integer.valueOf(dateColStr); result = new Integer(Integer.valueOf(dateColStr)); } else { result = new Long(dateColVal); } if (dateColVal < minTime) { minTime = dateColVal; } if (dateColVal > maxTime) { maxTime = dateColVal; } return result; }
/** * Converts this object to a <code>LocalDateTime</code> with * the same datetime and chronology. * * @return a LocalDateTime with the same datetime and chronology * @since 1.3 */ public LocalDateTime toLocalDateTime() { return new LocalDateTime(getMillis(), getChronology()); }
private Optional<Timestamp> tryParseWithFormat(String strValue) { checkState(fmt != null); if (startingDateValue != null) { // reset value in case any date fields are missing from the date pattern MutableDateTime mdt = new MutableDateTime( startingDateValue, ISOChronology.getInstanceUTC()); // Using parseInto() avoids throwing exception when parsing, // allowing fallback to default timestamp parsing if custom patterns fail. int ret = fmt.parseInto(mdt, strValue, 0); // Only accept parse results if we parsed the entire string if (ret == strValue.length()) { return Optional.of(Timestamp.ofEpochMilli(mdt.getMillis())); } return Optional.empty(); } try { LocalDateTime dt = fmt.parseLocalDateTime(strValue); return Optional.of( Timestamp.ofEpochMilli( dt.toDateTime(ISOChronology.getInstanceUTC().getZone()).getMillis())); } catch (IllegalArgumentException e) { return Optional.empty(); } }
@Override public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider provider) throws IOException { switch (_serializationShape(provider)) { case FORMAT_STRING: gen.writeString(_format.createFormatter(provider).print(value)); break; case FORMAT_TIMESTAMP: { // copied from `LocalDateTimeDeserializer`... DateTimeZone tz = _format.isTimezoneExplicit() ? _format.getTimeZone() : DateTimeZone.forTimeZone(provider.getTimeZone()); gen.writeNumber(value.toDateTime(tz).getMillis()); } break; case FORMAT_ARRAY: // Timestamp here actually means an array of values gen.writeStartArray(); gen.writeNumber(value.year().get()); gen.writeNumber(value.monthOfYear().get()); gen.writeNumber(value.dayOfMonth().get()); gen.writeNumber(value.hourOfDay().get()); gen.writeNumber(value.minuteOfHour().get()); gen.writeNumber(value.secondOfMinute().get()); gen.writeNumber(value.millisOfSecond().get()); gen.writeEndArray(); } } }
public static double convertToSeconds(String time, String timeFormat, long timeOffsetMillis) { if (timeFormat.isEmpty()) { return Double.parseDouble(time) - timeOffsetMillis / 1000.; } DateTime dateTime = LocalDateTime.parse(time, DateTimeFormat.forPattern(timeFormat)).toDateTime(DateTimeZone.UTC); double timeInSeconds = (dateTime.getMillis() - timeOffsetMillis) / 1000.; LOG.debug("time={} --> dateTime={} --> seconds with offset=" + timeInSeconds, time, dateTime); return timeInSeconds; } }
private DateTime convertToDateTime(String time) { if (timeInputPattern.equalsIgnoreCase("1")) { return DateTime.now(DateTimeZone.UTC); } DateTime dateTime = LocalDateTime.parse(time, DateTimeFormat.forPattern(timeInputPattern)).toDateTime( DateTimeZone.UTC); LOG.debug("{} --> {}", time, dateTime); return dateTime; }
/** * Handle broken serialization from other tools. * @return the resolved object, not null */ private Object readResolve() { if (iChronology == null) { return new LocalDateTime(iLocalMillis, ISOChronology.getInstanceUTC()); } if (DateTimeZone.UTC.equals(iChronology.getZone()) == false) { return new LocalDateTime(iLocalMillis, iChronology.withUTC()); } return this; }
/** * Obtains a {@code LocalDateTime} set to the current system millisecond time * using <code>ISOChronology</code> in the default time zone. * The resulting object does not use the zone. * * @return the current date, not null * @since 2.0 */ public static LocalDateTime now() { return new LocalDateTime(); }
protected Calendar dateToCalendar(Date date, TimeZone offerTimeZone) { DateTimeZone offerDateTimeZone = DateTimeZone.forTimeZone(offerTimeZone); LocalDateTime offerDateTime = new LocalDateTime(date, offerDateTimeZone); Calendar calendar = new GregorianCalendar(offerTimeZone); calendar.set(Calendar.YEAR, offerDateTime.getYear()); calendar.set(Calendar.MONTH, offerDateTime.getMonthOfYear() - 1); calendar.set(Calendar.DAY_OF_MONTH, offerDateTime.getDayOfMonth()); calendar.set(Calendar.HOUR_OF_DAY, offerDateTime.getHourOfDay()); calendar.set(Calendar.MINUTE, offerDateTime.getMinuteOfHour()); calendar.set(Calendar.SECOND, offerDateTime.getSecondOfMinute()); calendar.get(Calendar.HOUR_OF_DAY);//do not delete this line calendar.get(Calendar.MINUTE); return calendar; }
/** * Get the date time as a <code>java.util.Date</code>. * <p> * The <code>Date</code> object created has exactly the same fields as this * date-time, except when the time would be invalid due to a daylight savings * gap. In that case, the time will be set to the earliest valid time after the gap. * <p> * In the case of a daylight savings overlap, the earlier instant is selected. * <p> * Converting to a JDK Date is full of complications as the JDK Date constructor * doesn't behave as you might expect around DST transitions. This method works * by taking a first guess and then adjusting. This also handles the situation * where the JDK time zone data differs from the Joda-Time time zone data. * * @return a Date initialised with this date-time, never null * @since 2.0 */ @SuppressWarnings("deprecation") public Date toDate() { int dom = getDayOfMonth(); Date date = new Date(getYear() - 1900, getMonthOfYear() - 1, dom, getHourOfDay(), getMinuteOfHour(), getSecondOfMinute()); date.setTime(date.getTime() + getMillisOfSecond()); return correctDstTransition(date, TimeZone.getDefault()); }
InternalParser parser = requireParser(); Chronology chrono = selectChronology(null).withUTC(); // always use UTC, avoiding DST gaps DateTimeParserBucket bucket = new DateTimeParserBucket(0, chrono, iLocale, iPivotYear, iDefaultYear); int newPos = parser.parseInto(bucket, text, 0); int parsedOffset = bucket.getOffsetInteger(); DateTimeZone parsedZone = DateTimeZone.forOffsetMillis(parsedOffset); chrono = chrono.withZone(parsedZone); } else if (bucket.getZone() != null) { chrono = chrono.withZone(bucket.getZone()); return new LocalDateTime(millis, chrono);
@Override public Date getDate(int index) { if (ac.isNull(index)) { return null; } org.joda.time.LocalDateTime date = new org.joda.time.LocalDateTime(ac.get(index), org.joda.time.DateTimeZone.UTC); return new Date(date.getYear() - 1900, date.getMonthOfYear() - 1, date.getDayOfMonth()); }