Java Code Examples for org.joda.time.DateTime.getMillis()

The following are Jave code examples for showing how to use getMillis() of the org.joda.time.DateTime class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: Equella   File: EchoUtils.java   Source Code and License Vote up 7 votes
public static String formatDuration(long duration)
{
	// Using Joda Time
	DateTime now = new DateTime(); // Now
	DateTime plus = now.plus(new Duration(duration * 1000));

	// Define and calculate the interval of time
	Interval interval = new Interval(now.getMillis(), plus.getMillis());
	Period period = interval.toPeriod(PeriodType.time());

	// Define the period formatter for pretty printing
	String ampersand = " & ";
	PeriodFormatter pf = new PeriodFormatterBuilder().appendHours().appendSuffix(ds("hour"), ds("hours"))
		.appendSeparator(" ", ampersand).appendMinutes().appendSuffix(ds("minute"), ds("minutes"))
		.appendSeparator(ampersand).appendSeconds().appendSuffix(ds("second"), ds("seconds")).toFormatter();

	return pf.print(period).trim();
}
 
Example 2
Project: DicomViewer   File: SortedListTools.java   Source Code and License Vote up 6 votes
public static Integer idOfClosest(final List<DateTime> list, final DateTime key, final int low, final int high) {
    // Cas particuliers
    if (list == null || list.isEmpty() || key == null || low > high) {
        return null;
    }
    // Evacuation des cas où la valeur serait hors de l'intervalle -----------
    if (list.size() == 1) {
        return 0;
    }
    if (list.get(low).getMillis() >= key.getMillis()) {
        return low;
    }
    if (list.get(high).getMillis() <= key.getMillis()) {
        return high;
    }

    int idx = binarySearch(list, key, low, high);
    if (idx < 0) {
        idx = -(idx) - 1;
        if (idx != 0 && idx < list.size()) {
            return (key.getMillis()  - list.get(idx - 1).getMillis()  <= list.get(idx).getMillis() - key.getMillis() ) ? idx - 1 : idx;
        }
        return null;
    }
    return idx;
}
 
Example 3
Project: QDrill   File: ShowFilesCommandResult.java   Source Code and License Vote up 6 votes
public ShowFilesCommandResult(String name,
                              boolean isDirectory,
                              boolean isFile,
                              long length,
                              String owner,
                              String group,
                              String permissions,
                              long accessTime,
                              long modificationTime) {
  this.name = name;
  this.isDirectory = isDirectory;
  this.isFile = isFile;
  this.length = length;
  this.owner = owner;
  this.group = group;
  this.permissions = permissions;

  // Get the timestamp in UTC because Drill's internal TIMESTAMP stores time in UTC
  DateTime at = new DateTime(accessTime).withZoneRetainFields(DateTimeZone.UTC);
  this.accessTime = new Timestamp(at.getMillis());

  DateTime mt = new DateTime(modificationTime).withZoneRetainFields(DateTimeZone.UTC);
  this.modificationTime = new Timestamp(mt.getMillis());
}
 
Example 4
Project: teasy   File: DateUtils.java   Source Code and License Vote up 5 votes
public static void waitForAssignmentDate(DateTimeZone dateTimeZone, DateTime date) {
    DateTime currentTime = new DateTime(dateTimeZone);
    DateTime dateWithTimeZone = date.withZoneRetainFields(dateTimeZone);
    if (dateWithTimeZone.getMillis() > currentTime.getMillis()) {
        TestUtils.waitForSomeTime((int) (dateWithTimeZone.getMillis() - currentTime.getMillis()), "Wait for date");
    }
}
 
Example 5
Project: app_secompufscar   File: InstagramAdapter.java   Source Code and License Vote up 5 votes
private String getFormattedTimeInstagram(Date data){
    DateTime d1 = new DateTime(data);
    DateTime d2 = DateTime.now();
    long difference = d2.getMillis() - d1.getMillis();
    DateTime d3 = new DateTime(difference);
    long days = TimeUnit.MILLISECONDS.toDays(d3.getMillis());
    long hours = TimeUnit.MILLISECONDS.toHours(d3.getMillis());
    String out  = "";
    if (hours < 24){
        out =  "HÁ " + String.valueOf(hours) + " HORAS.";
        if (hours < 0) {
            //TODO tentar entender esse bug, enquanto isso, gambiarra rs
            out = "5 DE JUNHO DE 2017";
        }
    } else if (days < 8) {
        out = "HÁ " +  String.valueOf(days) + " DIAS.";
    } else {
        SimpleDateFormat format = new SimpleDateFormat("d,MMMM,yyyy", new Locale("pt", "BR"));
        format.setTimeZone(TimeZone.getDefault());
        out = format.format(data);
        out = out.replace(",", " DE ");
        //TODO: corrigir espaçamento no layout e colocar tudo em maiuscula com semparador "DE"
    }
    out = out.toUpperCase();
    out = out.replace(" DE 2017", "");
    return out;
}
 
Example 6
Project: elasticsearch_my   File: DateRangeAggregationBuilder.java   Source Code and License Vote up 5 votes
private Double convertDateTime(DateTime dateTime) {
    if (dateTime == null) {
        return null;
    } else {
        return (double) dateTime.getMillis();
    }
}
 
Example 7
Project: elasticsearch_my   File: DateMathExpressionResolverTests.java   Source Code and License Vote up 5 votes
public void testExpression_CustomTimeZoneInSetting() throws Exception {
    DateTimeZone timeZone;
    int hoursOffset;
    int minutesOffset = 0;
    if (randomBoolean()) {
        hoursOffset = randomIntBetween(-12, 14);
        timeZone = DateTimeZone.forOffsetHours(hoursOffset);
    } else {
        hoursOffset = randomIntBetween(-11, 13);
        minutesOffset = randomIntBetween(0, 59);
        timeZone = DateTimeZone.forOffsetHoursMinutes(hoursOffset, minutesOffset);
    }
    DateTime now;
    if (hoursOffset >= 0) {
        // rounding to next day 00:00
        now = DateTime.now(UTC).plusHours(hoursOffset).plusMinutes(minutesOffset).withHourOfDay(0).withMinuteOfHour(0).withSecondOfMinute(0);
    } else {
        // rounding to today 00:00
        now = DateTime.now(UTC).withHourOfDay(0).withMinuteOfHour(0).withSecondOfMinute(0);
    }
    Settings settings = Settings.builder()
            .put("date_math_expression_resolver.default_time_zone", timeZone.getID())
            .build();
    DateMathExpressionResolver expressionResolver = new DateMathExpressionResolver(settings);
    Context context = new Context(this.context.getState(), this.context.getOptions(), now.getMillis());
    List<String> results = expressionResolver.resolve(context, Arrays.asList("<.marvel-{now/d{YYYY.MM.dd}}>"));
    assertThat(results.size(), equalTo(1));
    logger.info("timezone: [{}], now [{}], name: [{}]", timeZone, now, results.get(0));
    assertThat(results.get(0), equalTo(".marvel-" + DateTimeFormat.forPattern("YYYY.MM.dd").print(now.withZone(timeZone))));
}
 
Example 8
Project: sjk   File: CDNCacheImpl.java   Source Code and License Vote up 5 votes
@Override
public final long getCurrentTimeCloseToPrevInterval() {
    long keepMinute = System.currentTimeMillis() / interval * interval;
    DateTime dt = new DateTime(keepMinute);
    int min = dt.getMinuteOfHour();
    min = getPrevIntervalMinute(min);
    dt = dt.minuteOfHour().setCopy(min);
    return dt.getMillis();
}
 
Example 9
Project: raven   File: DateUtils.java   Source Code and License Vote up 5 votes
public static Timestamp convertTimestampFromStr(String dateStr)
{
	if(StringUtils.isEmpty(dateStr))
	{
		return null;
	}
	
	DateTime dt = parseDate(dateStr);
	
	return new Timestamp(dt.getMillis());
	
}
 
Example 10
Project: asura   File: DateCalculator.java   Source Code and License Vote up 5 votes
/**
 * 获取指定日期的当天的任意一毫秒
 *
 * @param date 指定的日期
 * @return
 */
public static long getMilliSecondOfDate(@NotNull Date date, int hourOfDay, int minuteOfHour, int secondOfMinute, int millisOfSecond) {
    Objects.requireNonNull(date, "date must not null");
    DateTime dateTime = new DateTime(date);
    dateTime = dateTime.withHourOfDay(hourOfDay).withMinuteOfHour(minuteOfHour).withSecondOfMinute(secondOfMinute).withMillisOfSecond(millisOfSecond);
    return dateTime.getMillis();
}
 
Example 11
Project: abhot   File: RangeAggregator.java   Source Code and License Vote up 5 votes
/**
 For YEARS, MONTHS, WEEKS, DAYS:
 Computes the timestamp of the first millisecond of the day
 of the timestamp.
 For HOURS,
 Computes the timestamp of the first millisecond of the hour
 of the timestamp.
 For MINUTES,
 Computes the timestamp of the first millisecond of the minute
 of the timestamp.
 For SECONDS,
 Computes the timestamp of the first millisecond of the second
 of the timestamp.
 For MILLISECONDS,
 returns the timestamp

 @param timestamp
 @return
 */
@SuppressWarnings("fallthrough")
private long alignRangeBoundary(long timestamp)
{
	DateTime dt = new DateTime(timestamp, m_timeZone);
	TimeUnit tu = m_sampling.getUnit();
	switch (tu)
	{
		case YEARS:
			dt = dt.withDayOfYear(1).withMillisOfDay(0);
			break;
		case MONTHS:
			dt = dt.withDayOfMonth(1).withMillisOfDay(0);
			break;
		case WEEKS:
			dt = dt.withDayOfWeek(1).withMillisOfDay(0);
			break;
		case DAYS:
		case HOURS:
		case MINUTES:
		case SECONDS:
			dt = dt.withHourOfDay(0);
			dt = dt.withMinuteOfHour(0);
			dt = dt.withSecondOfMinute(0);
		default:
			dt = dt.withMillisOfSecond(0);
			break;
	}
	return dt.getMillis();
}
 
Example 12
Project: DicomViewer   File: SliderTimeComponent.java   Source Code and License Vote up 5 votes
/**
 * Changement des bornes de l'animation
 * @param limitMin
 * @param limitMax 
 */
public void setMinAndMax(final DateTime limitMin, final DateTime limitMax) {
    if (!minLimitDragging && !minLimitSelected) {
        this.dateMinAsValue = (limitMin != null) ? (double)limitMin.getMillis() : null;
    }
    if (!maxLimitDragging && !maxLimitSelected) {
        this.dateMaxAsValue = (limitMax != null) ? (double)limitMax.getMillis() : null;
    }
}
 
Example 13
Project: sstable-adaptor   File: SimpleDateSerializer.java   Source Code and License Vote up 4 votes
public static int dateStringToDays(String source) throws MarshalException
{
    // Raw day value in unsigned int form, epoch @ 2^31
    if (rawPattern.matcher(source).matches())
    {
        try
        {
            long result = Long.parseLong(source);

            if (result < 0 || result > maxSupportedDays)
                throw new NumberFormatException("Input out of bounds: " + source);

            // Shift > epoch days into negative portion of Integer result for byte order comparability
            if (result >= Integer.MAX_VALUE)
                result -= byteOrderShift;

            return (int) result;
        }
        catch (NumberFormatException e)
        {
            throw new MarshalException(String.format("Unable to make unsigned int (for date) from: '%s'", source), e);
        }
    }

    // Attempt to parse as date string
    try
    {
        DateTime parsed = formatter.parseDateTime(source);
        long millis = parsed.getMillis();
        if (millis < minSupportedDateMillis)
            throw new MarshalException(String.format("Input date %s is less than min supported date %s", source, new LocalDate(minSupportedDateMillis).toString()));
        if (millis > maxSupportedDateMillis)
            throw new MarshalException(String.format("Input date %s is greater than max supported date %s", source, new LocalDate(maxSupportedDateMillis).toString()));

        return timeInMillisToDay(millis);
    }
    catch (IllegalArgumentException e1)
    {
        throw new MarshalException(String.format("Unable to coerce '%s' to a formatted date (long)", source), e1);
    }
}
 
Example 14
Project: TheNounProject   File: DateTimeConverter.java   Source Code and License Vote up 4 votes
@Override
public Long convertToDatabaseValue(DateTime entityProperty) {
    return entityProperty == null ? null : entityProperty.getMillis();
}
 
Example 15
Project: springboot-spwa-gae-demo   File: DateTimeToDateTest.java   Source Code and License Vote up 4 votes
private void verifyTransform(DateTime date) {
    Date expected = new Date(date.getMillis());
    assertThat(transformer.from(date), is(expected));
}
 
Example 16
Project: killbill-easytax-plugin   File: JodaDateTimeBinding.java   Source Code and License Vote up 4 votes
@Override
public Timestamp to(DateTime userObject) {
    return (userObject != null ? new Timestamp(userObject.getMillis()) : null);
}
 
Example 17
Project: DicomViewer   File: SliderTimeComponent.java   Source Code and License Vote up 4 votes
/**
 * Changement de la date selectionné dans la barre de temps
 * @param value 
 */
public void setDate(final DateTime value) {
    super.setValue(value != null ? value.getMillis() : 0);
    repaint();
}
 
Example 18
Project: cat-is-a-dog   File: Habit.java   Source Code and License Vote up 4 votes
/**
 * Check if habit is due on a particular date
 * @param date the date to test
 * @return the habit is due on date
 */
@Override
public boolean isTodo(DateTime date) {
    int dayOfWeek = DateUtil.GetDayOfWeek(date);
    return schedule.contains(dayOfWeek) && date.getMillis() >= startDate.getMillis();
}
 
Example 19
Project: osc-core   File: ReadWriteLockRecord.java   Source Code and License Vote up 4 votes
private synchronized boolean getWriteLock(LockRequest lockRequest, boolean tryLock, long timeout)
        throws InterruptedException {
    this.waitingWriters++;

    DateTime start = new DateTime();
    long remainingWait = timeout;

    while (this.lockType == LockType.WRITE_LOCK || this.readLockCount > 0) {
        log.info("Current read lock count: " + this.readLockCount);

        if (tryLock) {
            this.waitingWriters--;
            return false;
        } else if (timeout > 0) {
            if (new DateTime().getMillis() - start.getMillis() >= timeout) {
                log.info("Waiting for lock " + lockRequest + " timed out.");
                this.waitingWriters--;
                return false;
            } else {
                remainingWait = timeout - (new DateTime().getMillis() - start.getMillis());
            }
        }

        try {
            log.info("Waiting for lock " + lockRequest);
            if (timeout > 0) {
                wait(remainingWait);
            } else {
                wait();
            }
            log.info("Notified of lock release " + lockRequest);
        } catch (InterruptedException e) {
            this.waitingWriters--;
            throw e;
        }
    }

    log.info("Gained Write lock " + lockRequest);
    this.waitingWriters--;
    setLockType(LockType.WRITE_LOCK);
    this.lockRequestsMap.put(lockRequest.getUnlockTask(), lockRequest);
    return true;
}
 
Example 20
Project: flume-release-1.7.0   File: SyslogParser.java   Source Code and License Vote up 4 votes
/**
 * 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
 */
protected long parseRfc3164Time(String ts) {
  DateTime now = DateTime.now();
  int year = now.getYear();

  ts = TWO_SPACES.matcher(ts).replaceFirst(" ");

  DateTime date;
  try {
    date = rfc3164Format.parseDateTime(ts);
  } catch (IllegalArgumentException e) {
    logger.debug("rfc3164 date parse failed on (" + ts + "): invalid format", e);
    return 0;
  }

  // rfc3164 dates are really dumb.
  /*
   * Some code to try and add some smarts to the year insertion as without a year in the message
   * we need to make some educated guessing.
   * First set the "fixed" to be the timestamp with the current year.
   * If the "fixed" time is more than one month in the future then roll it back a year.
   * If the "fixed" time is more than eleven months in the past then roll it forward a year.
   * This gives us a 12 month rolling window (11 months in the past, 1 month in the future) of
   * timestamps.
   */

  if (date != null) {
    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.minusYears(1);
    // flume clock is behind and the year rolled
    } else if (fixed.isBefore(now) && fixed.plusMonths(1).isBefore(now)) {
      fixed = date.plusYears(1);
    }
    date = fixed;
  }

  if (date == null) {
    return 0;
  }

  return date.getMillis();
}