Example usage for org.joda.time DateTime DateTime

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

Introduction

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

Prototype

public DateTime(Object instant) 

Source Link

Document

Constructs an instance from an Object that represents a datetime.

Usage

From source file:app.rappla.calendar.Date.java

License:Open Source License

/**
 * Constructor//from  w w w.  j  a  v  a 2s  .  co  m
 * 
 * @param icalStr
 *            One or more lines of iCalendar that specifies a date
 * @param parseMode
 *            PARSE_STRICT or PARSE_LOOSE
 */
public Date(String icalStr) throws ParseException, BogusDataException {
    super(icalStr);

    year = month = day = 0;
    hour = minute = second = 0;

    for (int i = 0; i < attributeList.size(); i++) {
        Attribute a = attributeAt(i);
        String aname = a.name.toUpperCase(Locale.ENGLISH);
        String aval = a.value.toUpperCase(Locale.ENGLISH);
        // TODO: not sure if any attributes are allowed here...
        // Look for VALUE=DATE or VALUE=DATE-TIME
        // DATE means untimed for the event
        if (aname.equals("VALUE")) {
            if (aval.equals("DATE")) {
                dateOnly = true;
            } else if (aval.equals("DATE-TIME")) {
                dateOnly = false;
            }
        } else if (aname.equals("TZID")) {
            tzid = a.value;
        } else {
            // TODO: anything else allowed here?
        }
    }

    String inDate = value;

    if (inDate.length() < 8) {
        // Invalid format
        throw new ParseException("Invalid date format '" + inDate + "'", inDate);
    }

    // Make sure all parts of the year are numeric.
    for (int i = 0; i < 8; i++) {
        char ch = inDate.charAt(i);
        if (ch < '0' || ch > '9') {
            throw new ParseException("Invalid date format '" + inDate + "'", inDate);
        }
    }
    year = Integer.parseInt(inDate.substring(0, 4));
    month = Integer.parseInt(inDate.substring(4, 6));
    day = Integer.parseInt(inDate.substring(6, 8));
    if (day < 1 || day > 31 || month < 1 || month > 12)
        throw new BogusDataException("Invalid date '" + inDate + "'", inDate);
    // Make sure day of month is valid for specified month
    if (year % 4 == 0) {
        // leap year
        if (day > leapMonthDays[month - 1]) {
            throw new BogusDataException("Invalid day of month '" + inDate + "'", inDate);
        }
    } else {
        if (day > monthDays[month - 1]) {
            throw new BogusDataException("Invalid day of month '" + inDate + "'", inDate);
        }
    }
    // TODO: parse time, handle localtime, handle timezone
    if (inDate.length() > 8) {
        // TODO make sure dateOnly == false
        if (inDate.charAt(8) == 'T') {
            try {
                hour = Integer.parseInt(inDate.substring(9, 11));
                minute = Integer.parseInt(inDate.substring(11, 13));
                second = Integer.parseInt(inDate.substring(13, 15));
                if (hour > 23 || minute > 59 || second > 59) {
                    throw new BogusDataException("Invalid time in date string '" + inDate + "'", inDate);
                }
                if (inDate.length() > 15) {
                    isUTC = inDate.charAt(15) == 'Z';
                }
            } catch (NumberFormatException nef) {
                throw new BogusDataException("Invalid time in date string '" + inDate + "' - " + nef, inDate);
            }
        } else {
            // Invalid format
            throw new ParseException("Invalid date format '" + inDate + "'", inDate);
        }
    } else {
        // Just date, no time
        dateOnly = true;
    }

    if (isUTC && !dateOnly) {
        // Use Joda Time to convert UTC to localtime
        DateTime utcDateTime = new DateTime(DateTimeZone.UTC);
        utcDateTime = utcDateTime.withDate(year, month, day).withTime(hour, minute, second, 0);
        DateTime localDateTime = utcDateTime.withZone(DateTimeZone.getDefault());
        year = localDateTime.getYear();
        month = localDateTime.getMonthOfYear();
        day = localDateTime.getDayOfMonth();
        hour = localDateTime.getHourOfDay();
        minute = localDateTime.getMinuteOfHour();
        second = localDateTime.getSecondOfMinute();
    } else if (tzid != null) {
        DateTimeZone tz = DateTimeZone.forID(tzid);
        if (tz != null) {
            // Convert to localtime
            DateTime utcDateTime = new DateTime(tz);
            utcDateTime = utcDateTime.withDate(year, month, day).withTime(hour, minute, second, 0);
            DateTime localDateTime = utcDateTime.withZone(DateTimeZone.getDefault());
            year = localDateTime.getYear();
            month = localDateTime.getMonthOfYear();
            day = localDateTime.getDayOfMonth();
            hour = localDateTime.getHourOfDay();
            minute = localDateTime.getMinuteOfHour();
            second = localDateTime.getSecondOfMinute();
            // Since we have converted to localtime, remove the TZID
            // attribute
            this.removeNamedAttribute("TZID");
        }
    }
    isUTC = false;

    // Add attribute that says date-only or date with time
    if (dateOnly)
        addAttribute("VALUE", "DATE");
    else
        addAttribute("VALUE", "DATE-TIME");

}

From source file:app.service.AuthService.java

License:Apache License

public int checkIfAuth(CryptoToken cryptoToken) {
    AccountSession expireSession = getSessionWithCheck(cryptoToken, true);
    if (expireSession == null) {
        return ResultCode.INVALID_TOKEN;
    }//from w ww .j  ava2s. co m

    DateTime now = DateTime.now();
    DateTime deadline = new DateTime(expireSession.getExpireTime());
    if (now.isBefore(deadline) || now.isEqual(deadline)) {
        return BaseResponse.COMMON_SUCCESS;
    }

    return ResultCode.OVERDUE_TOKEN;
}

From source file:app.service.AuthService.java

License:Apache License

public String checkIfAuthBind(CryptoToken cryptoToken) {
    AccountSession expireSession = getSessionWithCheck(cryptoToken, true);
    if (expireSession == null) {
        return null;
    }/* w  ww .  j av  a2s .co  m*/

    DateTime now = DateTime.now();
    DateTime deadline = new DateTime(expireSession.getExpireTime());
    if (now.isBefore(deadline) || now.isEqual(deadline)) {
        return expireSession.getUserId();
    }

    return null;
}

From source file:app.service.AuthService.java

License:Apache License

public int refreshExpireToken(CryptoToken cryptoToken, AccessResponse accessResponse) {
    AccountSession refreshSession = getSessionWithCheck(cryptoToken, false);
    if (refreshSession == null) {
        return ResultCode.INVALID_TOKEN;
    }//from  ww  w .j  a  v  a  2  s  .com

    // ? refreshToken
    DateTime now = DateTime.now();
    DateTime deadline = new DateTime(refreshSession.getRefreshTime());
    if (now.isAfter(deadline)) {
        return ResultCode.OVERDUE_TOKEN;
    }

    //  expireToken
    final long expireTime = now.plusHours(EXPIRE_TIME).getMillis();
    refreshSession.setExpireTime(expireTime);
    CryptoToken expireToken = newSessionToken(refreshSession, true);
    if (expireToken == null) {
        return ResultCode.ENCRYPT_TOKEN_FAILED;
    }

    accessResponse.setExpireTime(expireTime);
    accessResponse.setExpireToken(expireToken);
    return BaseResponse.COMMON_SUCCESS;
}

From source file:app.sunstreak.yourpisd.util.DateHelper.java

License:Open Source License

public static String timeSince(long millis) {
    return timeSince(new DateTime(millis));
}

From source file:ar.com.informaticaorion.sasha.beans.CollectionsBean.java

private int getDelay(Ticket ticket) {
    DateTime dtCollectionDate = new DateTime(this.getCollectionActivo().getCollectionDate());
    DateTime dtTicketDueDate = new DateTime(ticket.getDueDate());
    int delay = Days
            .daysBetween(dtTicketDueDate.withTimeAtStartOfDay(), dtCollectionDate.withTimeAtStartOfDay())
            .getDays();//from w  w  w . java  2  s  . com
    return delay;
}

From source file:ar.com.zir.utils.DateUtils.java

License:Open Source License

/**
 * Method that uses Joda Library to obtain the difference between two dates
 * in the specified date part/*from   w  ww  .  ja  v a2  s.co m*/
 * 
 * @param datePart the datePart to use in the calculation
 * @param date1 first Date object
 * @param date2 second Date object
 * @return the result from date1 - date2 or -1 if specified datePart is not supported
 * @see java.util.Calendar
 */
public static int dateDiff(int datePart, Date date1, Date date2) {
    Calendar cal1 = Calendar.getInstance();
    cal1.setTime(date1);
    Calendar cal2 = Calendar.getInstance();
    cal2.setTime(date2);
    switch (datePart) {
    case DATE_PART_SECOND:
        return Seconds
                .secondsBetween(new DateTime(cal2.getTimeInMillis()), new DateTime(cal1.getTimeInMillis()))
                .getSeconds();
    case DATE_PART_MINUTE:
        return Minutes
                .minutesBetween(new DateTime(cal2.getTimeInMillis()), new DateTime(cal1.getTimeInMillis()))
                .getMinutes();
    case DATE_PART_HOUR:
        return Hours.hoursBetween(new DateTime(cal2.getTimeInMillis()), new DateTime(cal1.getTimeInMillis()))
                .getHours();
    case DATE_PART_DAY:
        return Days.daysBetween(new DateTime(cal2.getTimeInMillis()), new DateTime(cal1.getTimeInMillis()))
                .getDays();
    case DATE_PART_MONTH:
        return Months.monthsBetween(new DateTime(cal2.getTimeInMillis()), new DateTime(cal1.getTimeInMillis()))
                .getMonths();
    case DATE_PART_YEAR:
        return Years.yearsBetween(new DateTime(cal2.getTimeInMillis()), new DateTime(cal1.getTimeInMillis()))
                .getYears();
    default:
        return -1;
    }

}

From source file:at.florian_lentsch.expirysync.net.ServerProxy.java

License:Open Source License

public void createProductEntry(final ProductEntry entry, ArrayList<ArticleImage> imageList,
        final ProductEntryCallback callback) {
    JSONObject paramObj = this.entryToJson(entry, imageList);

    final JsonCallOptions jsonCallParam = new JsonCallOptions();
    jsonCallParam.method = JsonCaller.METHOD_POST;
    jsonCallParam.path = "product_entries";
    jsonCallParam.params = paramObj;/*from w  w w.j  a  v  a2  s.  c o  m*/
    jsonCallParam.callback = new JsonCallback() {
        @Override
        public void onReceive(JSONObject receivedObj) {
            try {
                SimpleDateFormat sdfToDate = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
                SimpleDateFormat sdfToDateTime = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);

                JSONObject entryObj = receivedObj.getJSONObject("product_entry");
                entry.serverId = entryObj.getInt("id");
                entry.description = entryObj.getString("description");
                entry.amount = entryObj.getInt("amount");
                entry.expiration_date = sdfToDate.parse(entryObj.getString("expiration_date"));
                entry.created_at = new DateTime(sdfToDateTime.parse(entryObj.getString("created_at")));
                entry.updated_at = new DateTime(sdfToDateTime.parse(entryObj.getString("updated_at")));
                JSONObject articleObj = entryObj.getJSONObject("article");
                entry.article.name = articleObj.isNull("name") ? null : articleObj.getString("name");
                entry.article.barcode = articleObj.isNull("barcode") ? null : articleObj.getString("barcode");
            } catch (Exception e) {
                e.printStackTrace();
                callback.onReceive(null);
                return;
            }
            callback.onReceive(entry);
        }
    };

    (new JsonCallTask()).execute(jsonCallParam);
}

From source file:at.florian_lentsch.expirysync.net.ServerProxy.java

License:Open Source License

public void updateProductEntry(final ProductEntry entry, ArrayList<ArticleImage> imageList,
        final ProductEntryCallback callback) {
    JSONObject paramObj = this.entryToJson(entry, imageList);

    final JsonCallOptions jsonCallParam = new JsonCallOptions();
    jsonCallParam.method = JsonCaller.METHOD_PUT;
    jsonCallParam.path = "product_entries/" + entry.serverId;
    jsonCallParam.params = paramObj;/* www.ja  v a2s.c  om*/
    jsonCallParam.callback = new JsonCallback() {
        @Override
        public void onReceive(JSONObject receivedObj) {
            try {
                SimpleDateFormat sdfToDate = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
                SimpleDateFormat sdfToDateTime = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);

                JSONObject entryObj = receivedObj.getJSONObject("product_entry");
                entry.serverId = entryObj.getInt("id");
                entry.description = entryObj.getString("description");
                entry.amount = entryObj.getInt("amount");
                entry.expiration_date = sdfToDate.parse(entryObj.getString("expiration_date"));
                entry.created_at = new DateTime(sdfToDateTime.parse(entryObj.getString("created_at")));
                entry.updated_at = new DateTime(sdfToDateTime.parse(entryObj.getString("updated_at")));

                JSONObject articleObj = entryObj.getJSONObject("article");
                entry.article.name = articleObj.isNull("name") ? null : articleObj.getString("name");
                entry.article.barcode = articleObj.isNull("barcode") ? null : articleObj.getString("barcode");
            } catch (Exception e) {
                e.printStackTrace();
                callback.onReceive(null);
                return;
            }
            callback.onReceive(entry);
        }
    };

    (new JsonCallTask()).execute(jsonCallParam);
}

From source file:at.florian_lentsch.expirysync.net.ServerProxy.java

License:Open Source License

public void deleteProductEntry(final ProductEntry entry, final ProductEntryCallback callback) {
    final JsonCallOptions jsonCallParam = new JsonCallOptions();
    jsonCallParam.method = JsonCaller.METHOD_DELETE;
    jsonCallParam.path = "product_entries/" + entry.serverId;
    jsonCallParam.callback = new JsonCallback() {
        @Override/*from w w w.  j  a  v a  2 s.co  m*/
        public void onReceive(JSONObject receivedObj) {
            try {
                JSONObject entryObj = receivedObj.getJSONObject("product_entry");
                SimpleDateFormat sdfToDateTime = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
                entry.serverId = entryObj.getInt("id");
                entry.deleted_at = new DateTime(sdfToDateTime.parse(entryObj.getString("deleted_at")));
            } catch (Exception e) {
                e.printStackTrace();
            }
            callback.onReceive(entry);
        }
    };

    (new JsonCallTask()).execute(jsonCallParam);
}