Example usage for org.joda.time DateTime toDateTime

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

Introduction

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

Prototype

public DateTime toDateTime(Chronology chronology) 

Source Link

Document

Get this object as a DateTime, returning this if possible.

Usage

From source file:monasca.common.hibernate.db.AbstractAuditablePersistable.java

License:Apache License

/**
 * Null-safe method that transform {@link DateTime} into plain {@link java.util.Date}
 *
 * @param value DateTime instance/*w w  w  .j  av  a  2s  . c  o m*/
 *
 * @return plain Date
 *
 * @see #nullSafeGetDate(Date)
 */
static Date nullSafeSetDate(@Nullable final DateTime value) {
    if (value == null) {
        return null;
    }
    return value.toDateTime(DateTimeZone.UTC).toDate();
}

From source file:monasca.common.hibernate.db.AbstractAuditablePersistable.java

License:Apache License

/**
 * Ensures that both {@link #createdAt} and {@link #updatedAt} will be
 * set to the earliest possible value in case passed values are {@code NULL}
 *
 * @param createdAt created date/*from  www .j a  v a2 s. co  m*/
 * @param updatedAt updated date
 */
private void setDates(final DateTime createdAt, final DateTime updatedAt) {
    final Date date = DateTime.now(DateTimeZone.UTC).toDate();
    if (createdAt == null) {
        this.createdAt = date;
    } else {
        this.createdAt = createdAt.toDateTime(DateTimeZone.UTC).toDate();
    }
    if (updatedAt == null) {
        this.updatedAt = date;
    } else {
        this.updatedAt = updatedAt.toDateTime(DateTimeZone.UTC).toDate();
    }
}

From source file:net.schweerelos.timeline.model.Timeline.java

License:Open Source License

public void setInterval(DateTime start, DateTime end) {
    DateTimeZone defaultTimeZone = DateTimeZone.getDefault();

    // make sure we don't start before the start of the intervals (in years)
    DateTime firstStart = allIntervals.getFirstStart();
    firstStart = firstStart.withDayOfYear(firstStart.dayOfYear().getMinimumValue());
    if (start != null && start.toDateTime(defaultTimeZone).isBefore(firstStart)) {
        this.start = firstStart;
    } else {/*from   www .ja v a 2  s  .  c om*/
        this.start = start;
    }

    // make sure we don't end after the end of the intervals (in years)
    DateTime lastEnd = allIntervals.getLastEnd();
    lastEnd = lastEnd.withDayOfYear(lastEnd.dayOfYear().getMaximumValue());
    if (end != null && end.toDateTime(defaultTimeZone).isAfter(lastEnd)) {
        this.end = lastEnd;
    } else {
        this.end = end;
    }

    recalculate();
}

From source file:nl.knaw.dans.common.solr.SolrUtil.java

License:Apache License

public static String toString(final DateTime d) {
    DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
    DateTime dUtc = d.toDateTime(DateTimeZone.UTC);
    return fmt.print(dUtc);
}

From source file:nz.al4.airclock.MainActivity.java

License:Open Source License

@Override
public void onAlarmTimePicked(int hour, int minute) {

    DateTime currentTime = DateTime.now().toDateTime(mTimeCalculator.getTimeZone());
    Log.v("alarmCalc", "current time" + currentTime.toString());
    MutableDateTime desiredTime = currentTime.toMutableDateTime();
    desiredTime.setHourOfDay(hour);//  w  w  w .ja va 2  s  . c om
    desiredTime.setMinuteOfHour(minute);

    // if after we set the hour + minute we get an earlier time, user probably means next day
    if (desiredTime.isBefore(currentTime)) {
        desiredTime.addDays(1);
    }

    DateTime alarmTime = mTimeCalculator.timeForAlarm(desiredTime.toDateTime().toLocalDateTime());

    DateTime originAlarm = alarmTime.toDateTime(mTimeCalculator.mOriginTime.getZone());
    DateTime destAlarm = alarmTime.toDateTime(mTimeCalculator.mDestTime.getZone());

    String msg = String.format("You should set your alarm for:\n%s (origin)\nor\n%s (destination)",
            dateTimeFormatter.print(originAlarm) + " " + originAlarm.getZone().toString(),
            dateTimeFormatter.print(destAlarm) + " " + destAlarm.getZone().toString());

    new AlertDialog.Builder(this).setTitle("Alarm").setMessage(msg).setCancelable(false)
            .setPositiveButton("ok", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // Whatever...
                }
            }).show();
}

From source file:nz.al4.airclock.TimeCalculator.java

License:Open Source License

/**
 * Calculate when to set an alarm given a LocalDateTime (no time zone information)
 *
 * To do this, we need to figure out what time zone will be applied when we hit this time...
 * far from trivial!//from www.j  av a2s.  c o m
 *
 * So we use linear algebra to create simple formulas for the absolute time and tz offet of our
 * alarm.
 *
 * @param localAlarmTime
 * @return
 */
public DateTime timeForAlarm(LocalDateTime localAlarmTime) {
    Log.d("timeForAlarm", "Calculating alarm for time " + localAlarmTime.toString());
    // x axis, Time in ms since 1970
    long To = mOriginTime.getMillis(); // x1
    long Td = mDestTime.getMillis(); // x3
    // y axis, Offset in milliseconds
    long Oo = mOriginTime.getZone().getOffset(mOriginTime); // y1
    long Od = mDestTime.getZone().getOffset(mDestTime); // y3

    System.out.println(String.valueOf(To) + ',' + String.valueOf(Oo));
    System.out.println(String.valueOf(Td) + ',' + String.valueOf(Od));

    // slope = x/y
    float slope = (Td - To) / (Od - Oo);
    Log.v("debug", String.valueOf(slope));
    System.out.println(String.valueOf(slope));

    /*
    now that we have the slope, we can use algebra to rearrange what we know and come up
    with formulas for what we don't.
            
    * (x1, y1) is the point at takeoff, i.e (To, Oo)
    * our unknown point, the alarm point is (x2, y2) => (Ta, Oa) (Time of alarm,
      offset of alarm)
    * the localtime of the alarm we want to calculate, T, equals x2 (absolute time at
      alarm) plus y2 (offset at time of alarm)
    (tz offset at alarm time), i.e T=x2+y2
            
    by rearranging the slope formula, y2 = (x2 - x1)/S + y1
    therefore T - x2  = (x2 - x1)/S + y1 etc, until we get the formulas below
    */

    // UTC is zero offset,
    long T = localAlarmTime.toDateTime(DateTimeZone.UTC).getMillis();
    System.out.println("T " + String.valueOf(T));
    double Ta = ((slope * To) - Oo + T) / (slope + 1);
    System.out.println("Ta " + String.valueOf(Ta));
    // y2 = T - x2
    double Oa = T - Ta;
    System.out.println("Oa " + String.valueOf(Oa));

    // construct a datetime
    DateTimeZone alarmTz = DateTimeZone.forOffsetMillis((int) Oa);
    DateTime alarmTime = new DateTime((long) Ta, alarmTz);
    Log.d("timeForAlarm", "as origin: " + alarmTime.toDateTime(mOriginTime.getZone()).toString());
    Log.d("timeForAlarm", "as dest: " + alarmTime.toDateTime(mDestTime.getZone()).toString());

    return alarmTime;
}

From source file:org.aludratest.cloud.web.report.ResourceReportUtil.java

License:Apache License

public static JavaScriptArray getResourceUsageData(ResourceType resourceType, DateTime startTime,
        DateTime endTime, long tolerance) throws SQLException {
    startTime = startTime.toDateTime(DateTimeZone.UTC);
    endTime = endTime.toDateTime(DateTimeZone.UTC);
    String tp = resourceType.getName();

    // get active count at start time
    String startTimeStr = startTime.toString(DB_DATE_FORMAT);
    String sql = "SELECT count(*) FROM app.acm_request WHERE start_work_time_utc <= '" + startTimeStr
            + "' AND end_work_time_utc > '" + startTimeStr + "' AND resource_type = '" + tp + "'";

    RowSet rs = CloudManagerApplicationHolder.getInstance().getDatabase().populateQuery(sql);
    int initialCount = 0;
    if (rs.next()) {
        initialCount = rs.getInt(1);//  w ww .ja  v a2  s .  co  m
    }

    // iterate over all entries starting or ending in this interval
    sql = "SELECT start_work_time_utc, end_work_time_utc FROM acm_request WHERE resource_type = '" + tp
            + "' AND (start_work_time_utc >= '" + startTimeStr + "' AND end_work_time_utc < '"
            + endTime.toString(DB_DATE_FORMAT) + "') OR (start_work_time_utc <= '" + startTimeStr
            + "' AND end_work_time_utc > '" + startTimeStr + "') ORDER BY start_work_time_utc";

    rs = CloudManagerApplicationHolder.getInstance().getDatabase().populateQuery(sql);

    JavaScriptArray data = new JavaScriptArray();

    int activeResources = initialCount;

    // first entry
    data.add(createTimeEntry(startTime, activeResources));

    // build a full list of "delta" events
    List<ActiveResourcesDeltaEvent> events = new ArrayList<ActiveResourcesDeltaEvent>(2000);

    while (rs.next()) {
        DateTime dtStart = new DateTime(rs.getTimestamp(1).getTime()).withZoneRetainFields(DateTimeZone.UTC);
        DateTime dtEnd = new DateTime(rs.getTimestamp(2).getTime()).withZoneRetainFields(DateTimeZone.UTC);

        if (!dtStart.isBefore(startTime)) {
            events.add(new ActiveResourcesDeltaEvent(dtStart, 1));
        }
        events.add(new ActiveResourcesDeltaEvent(dtEnd, -1));
    }

    // compress event list to data series
    Collections.sort(events);

    DateTime currentTime = null;
    int currentDelta = 0;

    for (ActiveResourcesDeltaEvent event : events) {
        if (!sameTimePoint(currentTime, event.dt, tolerance)) {
            if (currentTime != null && currentDelta != 0) {
                // also add a helper point
                data.add(createTimeEntry(new DateTime(currentTime.getMillis() - 1), activeResources));
                activeResources += currentDelta;
                data.add(createTimeEntry(currentTime, activeResources));
            }
            currentTime = event.dt;
            currentDelta = event.resourcesDelta;
        } else {
            currentDelta += event.resourcesDelta;
        }
    }

    if (currentTime != null && currentDelta != 0) {
        if (activeResources == 0) {
            data.add(createTimeEntry(new DateTime(currentTime.getMillis() - 1), 0));
        }
        activeResources += currentDelta;
        data.add(createTimeEntry(currentTime, activeResources));
    }

    if (activeResources == 0) {
        // add end point
        data.add(createTimeEntry(endTime, 0));
    }

    return data;
}

From source file:org.aludratest.cloud.web.report.ResourceReportUtil.java

License:Apache License

private static JavaScriptObject createTimeEntry(DateTime time, int activeResources) {
    JavaScriptObject result = new JavaScriptObject();
    time = time.toDateTime(DateTimeZone.UTC);

    // convert time to JavaScript UTC time
    StringBuilder sbDateTime = new StringBuilder();
    sbDateTime.append("Date.UTC(");
    sbDateTime.append(time.getYear()).append(", ");
    sbDateTime.append(time.getMonthOfYear() - 1).append(", ");
    sbDateTime.append(time.getDayOfMonth()).append(", ");
    sbDateTime.append(time.getHourOfDay()).append(", ");
    sbDateTime.append(time.getMinuteOfHour()).append(", ");
    sbDateTime.append(time.getSecondOfMinute()).append(", ");
    sbDateTime.append(time.getMillisOfSecond()).append(")");

    result.set("x", new JavaScriptCodeFragment(sbDateTime.toString()));
    result.set("y", new JavaScriptCodeFragment("" + activeResources));

    return result;
}

From source file:org.apache.abdera2.common.date.DateTimes.java

License:Apache License

/**
 * Converts the given DateTime to the UTC TimeZone
 *//*from   ww w .j a va  2 s  .  c o  m*/
public static DateTime toUTC(DateTime dt) {
    return dt.toDateTime(DateTimeZone.UTC);
}

From source file:org.apache.abdera2.common.date.DateTimes.java

License:Apache License

/**
 * Converts the given DateTime to the given TimeZone
 *//*from  www.  j  a v a  2  s.c  o m*/
public static DateTime toTimeZone(DateTime dt, TimeZone tz) {
    return dt.toDateTime(DateTimeZone.forTimeZone(tz));
}