List of usage examples for org.joda.time DateTime getMillis
public long getMillis()
From source file:controllers.api.SearchApiController.java
License:Open Source License
/** * Create a list with histogram results that would be serialized to JSON like this * <p/>//from w w w. java 2 s . c om * [{ x: -1893456000, y: 92228531 }, { x: -1577923200, y: 106021568 }] */ protected List<Map<String, Long>> formatHistogramResults(DateHistogramResult histogram, int maxDataPoints, boolean allQuery) { final List<Map<String, Long>> points = Lists.newArrayList(); final Map<String, Long> histogramResults = histogram.getResults(); DateTime from; if (allQuery) { String firstTimestamp = histogramResults.entrySet().iterator().next().getKey(); from = new DateTime(Long.parseLong(firstTimestamp) * 1000, DateTimeZone.UTC); } else { from = DateTime.parse(histogram.getHistogramBoundaries().getFrom()); } final DateTime to = DateTime.parse(histogram.getHistogramBoundaries().getTo()); final MutableDateTime currentTime = new MutableDateTime(from); final Duration step = estimateIntervalStep(histogram.getInterval()); final int dataPoints = (int) ((to.getMillis() - from.getMillis()) / step.getMillis()); // using the absolute value guarantees, that there will always be enough values for the given resolution final int factor = (maxDataPoints != -1 && dataPoints > maxDataPoints) ? dataPoints / maxDataPoints : 1; int index = 0; floorToBeginningOfInterval(histogram.getInterval(), currentTime); while (currentTime.isBefore(to) || currentTime.isEqual(to)) { if (index % factor == 0) { String timestamp = Long.toString(currentTime.getMillis() / 1000); Long result = histogramResults.get(timestamp); Map<String, Long> point = Maps.newHashMap(); point.put("x", Long.parseLong(timestamp)); point.put("y", result != null ? result : 0); points.add(point); } index++; nextStep(histogram.getInterval(), currentTime); } return points; }
From source file:cron.DayOfWeekField.java
License:Open Source License
public boolean matches(DateTime time) { if (unspecified) return true; final int dayOfWeek = time.getDayOfWeek(); int number = number(dayOfWeek); if (hasLast) { return last.contains(number) && time.getMonthOfYear() != time.plusWeeks(1).getMonthOfYear(); } else if (hasNth) { for (int possibleMatch : nth.get(number)) { DateTime midnight = time.withTimeAtStartOfDay(); DateTime first = midnight.withDayOfMonth(1).withDayOfWeek(dayOfWeek); if (first.getMonthOfYear() != time.getMonthOfYear()) first = first.plusWeeks(1); DateTime tomorrow = midnight.plusDays(1); int weekNumber = 1 + (int) ((tomorrow.getMillis() - first.getMillis()) / MILLISECONDS_PER_WEEK); if (possibleMatch == weekNumber) return true; }//from ww w .ja v a 2 s . c om } return contains(number); }
From source file:cz.cas.lib.proarc.common.workflow.model.TaskParameter.java
License:Open Source License
public void setValue(String value) throws WorkflowException { if (valueType == ValueType.NUMBER) { BigDecimal number = null; if (value != null) { if ("true".equals(value)) { number = BigDecimal.ONE; } else if ("false".equals(value)) { number = BigDecimal.ZERO; } else { try { number = new BigDecimal(value); } catch (NumberFormatException ex) { throw new WorkflowException(value, ex).addParamNumberFormat(paramRef, value); }//from w w w . j ava2 s .c o m } } setValueNumber(number); } else if (valueType == ValueType.DATETIME) { Timestamp t = null; if (value != null) { try { DateTime dateTime = ISODateTimeFormat.dateOptionalTimeParser().withZoneUTC() .parseDateTime(value); t = new Timestamp(dateTime.getMillis()); } catch (IllegalArgumentException ex) { throw new WorkflowException(value, ex).addParamDateTimeFormat(paramRef, value); } } setValueDateTime(t); } else { // valueType == Type.STRING and others setValueString(value); } }
From source file:cz.krtinec.birthday.Utils.java
License:Open Source License
public static long calculateNotifTime(Long nowMillis, int hourToNotify) { DateTime now = new DateTime(nowMillis); DateTime timeToNotify = new DateTime(nowMillis); timeToNotify = timeToNotify.withHourOfDay(hourToNotify); if (timeToNotify.isBefore(now)) { timeToNotify = timeToNotify.plusDays(1); }/*from w w w .ja v a2s . co m*/ return timeToNotify.getMillis(); }
From source file:damo.three.ie.util.DateUtils.java
License:Open Source License
/** * Convert a date as {@link String} to milliseconds as {@link Long}. * * @param input Date as String/*w w w . j av a 2 s .c om*/ * @return Date object from inputted string. */ public static Long parseDate(String input) { if (input.equals("Today")) { return Calendar.getInstance().getTime().getTime(); } else if (input.equals("Won't expire**")) { return WONT_EXPIRE; } else if (input.equals("In queue")) { return QUEUED; } else if (input.equals("Expired")) { // for some reason people get usages with expire date of "Expired" // it will be filtered out later. return ALREADY_EXPIRED; } else { DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yy").withLocale(Locale.UK); DateTime dt = formatter.parseDateTime(input.replace("Expires ", "")); return dt.getMillis(); } }
From source file:damo.three.ie.util.DateUtils.java
License:Open Source License
/** * Converts an Out of Bundle date as string to {@link Long} * * @param outOfBundleDate Out of Bundle date * @return Out of bundle date as {@link Long} *//*from w w w. j av a2 s . com*/ public static Long parseOutOfBundleDate(String outOfBundleDate) { DateTimeFormatter formatter = DateTimeFormat.forPattern("dd MMMMM yyyy").withLocale(Locale.UK); DateTime dt = formatter.parseDateTime(outOfBundleDate); return dt.getMillis(); }
From source file:damo.three.ie.util.UsageUtils.java
License:Open Source License
/** * Register alarm when last internet data/add-on expires. * Clear alarms if they are no longer relevant. *///www.j a v a2 s .c om public static void registerInternetExpireAlarm(Context context, List<BasicUsageItem> usageItems, boolean notificationsEnabled, boolean obeyThreshold) { InternetUsageRegistry internetUsageRegistry = InternetUsageRegistry.getInstance(); internetUsageRegistry.clear(); /* For each Internet add-on, add it to InternetUsageRegistry */ for (BasicUsageItem b : usageItems) { if (b instanceof InternetAddon || b instanceof Data) { /* Make sure it's not expired first */ if (b.isExpirable() && b.isNotExpired()) { internetUsageRegistry.submit(b.getExpireDate()); } } } DateTime dateTime = internetUsageRegistry.getDateTime(); Intent intent = new Intent(context, InternetAddonExpireReceiver.class); // Add internet expire time to intent. We need this if the add-on expired while the phone was off. // We will use this to determine the appropriate information to show the user. if (dateTime != null) { intent.putExtra(InternetUsageRegistry.INTERNET_EXPIRE_TIME, internetUsageRegistry.getDateTime().getMillis()); } PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); // First check if anything is registered in internet registry and we want notifications if (internetUsageRegistry.getDateTime() != null && notificationsEnabled) { am.cancel(pendingIntent); //Set one-time alarm. 4 hours enough of a warning ? Decide if we wan't to make this configurable. DateTime internetExpires = internetUsageRegistry.getDateTime().minusHours(4); // If obeying threshold, don't show a notification if internet is expiring within 4 hours, as we already // showed a notification at the 4 hour to expiry mark. This prevents a notification every time the user // refreshes the usages while it is under 4 hours until expire time. if (obeyThreshold) { if (new DateTime().compareTo(internetExpires) < 0) { am.set(AlarmManager.RTC_WAKEUP, internetExpires.getMillis(), pendingIntent); } } else { // This option exists if we do want a notification shown within the 4 hour threshold. e.g. user turns on // the phone within the 4 hour threshold to expirey time. am.set(AlarmManager.RTC_WAKEUP, internetExpires.getMillis(), pendingIntent); } } else { am.cancel(pendingIntent); } }
From source file:DAO.AuctionDAO.java
public boolean add(Auction auction) { try {/*from w ww.ja v a2 s . co m*/ String sql = "INSERT INTO auction (category_id, seller_id, title, description, starting_price, buy_now_price, increase_by, img_cover, img_1, img_2, img_3, img_4, img_5, v_youtube, start_date, end_date) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,FROM_UNIXTIME(?),FROM_UNIXTIME(?)) "; pre = conn.prepareStatement(sql); pre.setInt(1, auction.getCategoryId()); pre.setInt(2, auction.getSellerId()); pre.setString(3, auction.getTitle()); pre.setString(4, auction.getDescription()); pre.setDouble(5, auction.getStartPrice()); pre.setDouble(6, auction.getBuynowPrice()); pre.setDouble(7, auction.getIncreaseBy()); pre.setString(8, auction.getImgCover()); pre.setString(9, auction.getImg1()); pre.setString(10, auction.getImg2()); pre.setString(11, auction.getImg3()); pre.setString(12, auction.getImg4()); pre.setString(13, auction.getImg5()); pre.setString(14, auction.getvYoutubeFull()); DateTime startDate = auction.getStartDate(); pre.setLong(15, startDate.getMillis() / 1000); DateTime endDate = auction.getEndDate(); pre.setLong(16, endDate.getMillis() / 1000); pre.executeUpdate(); return true; } catch (SQLException ex) { Logger.getLogger(AuctionDAO.class.getName()).log(Level.SEVERE, null, ex); System.out.println("Auction DAO, add failed."); return false; } }
From source file:DAO.AuctionDAO.java
public boolean update(Auction auction) { try {//from w w w . ja v a 2s .c om String sql = "UPDATE auction SET category_id = ?, seller_id = ?, title = ?, description = ?, starting_price = ?, buy_now_price = ?, increase_by = ?" + ", img_cover = ?, img_1 = ?, img_2 = ?, img_3 = ?, img_4 = ?, img_5 = ?, v_youtube = ?, start_date = FROM_UNIXTIME(?), " + "end_date = FROM_UNIXTIME(?), moderate_status = ?, views = ?, close_date = FROM_UNIXTIME(?), buyer_confirm = ? " + "WHERE auctionid = ? "; PreparedStatement pre = conn.prepareStatement(sql); pre.setInt(1, auction.getCategoryId()); pre.setInt(2, auction.getSellerId()); pre.setString(3, auction.getTitle()); pre.setString(4, auction.getDescription()); pre.setDouble(5, auction.getStartPrice()); pre.setDouble(6, auction.getBuynowPrice()); pre.setDouble(7, auction.getIncreaseBy()); pre.setString(8, auction.getImgCover()); pre.setString(9, auction.getImg1()); pre.setString(10, auction.getImg2()); pre.setString(11, auction.getImg3()); pre.setString(12, auction.getImg4()); pre.setString(13, auction.getImg5()); pre.setString(14, auction.getvYoutubeFull()); DateTime startDate = auction.getStartDate(); pre.setLong(15, startDate.getMillis() / 1000); DateTime endDate = auction.getEndDate(); pre.setLong(16, endDate.getMillis() / 1000); pre.setInt(17, auction.getModerateStatus()); pre.setInt(18, auction.getViews()); DateTime closeDate = auction.getCloseDate(); pre.setLong(19, closeDate.getMillis() / 1000); pre.setString(20, auction.getBuyerConfirm()); pre.setInt(21, auction.getId()); //System.out.println(auction.getCategoryId()); pre.executeUpdate(); return true; } catch (SQLException ex) { Logger.getLogger(AuctionDAO.class.getName()).log(Level.SEVERE, null, ex); System.out.println("Auction DAO, update failed."); return false; } }
From source file:DAO.AuctionDAO.java
public String processAuctions() { try {//from w w w . ja va 2 s. co m String result = ""; ArrayList<Auction> auctions = new ArrayList<>(); ArrayList<Auction> closedAuctions = new ArrayList<>(); String sql = "SELECT auctionid FROM auction WHERE moderate_status = 0 OR moderate_status = 3 "; PreparedStatement pre2 = conn.prepareStatement(sql); ResultSet rs2 = pre2.executeQuery(); while (rs2.next()) { int auctionId = rs2.getInt("auctionid"); Auction auction = this.getAuction(auctionId); DateTime today = new DateTime(); BidDAO bidDao = new BidDAO(); ArrayList<Bid> bids = bidDao.getBidFromAuctionId(auctionId, 1); if (auction.getStatus().equals("Closed")) { if (bids.size() > 0) { //if (auction.getCloseDate()) //int winnerId = bids.get(0).getBidderId(); String oldStatus = auction.getStatus(); auction.setModerateStatus(3); auction.setBuyerConfirm(""); auction.setCloseDate(today); if (this.update(auction)) { result = result + "- Auction ID #" + auction.getId() + " ('" + auction.getTitle() + "') has been sucessfully processed! [Status changed: " + oldStatus + " -> " + auction.getStatus() + "]<br>"; } else { result = result + "- Auction ID #" + auction.getId() + " ('" + auction.getTitle() + "') has failed to be processed properly!<br>"; } } } else if (auction.getStatus().equals("Pending approval")) { DateTime closeDate = auction.getCloseDate(); long diffInMillis = today.getMillis() - closeDate.getMillis(); long requiredInterval = 86400000 * 3; //3 days if (diffInMillis >= requiredInterval) { Bid bid = bids.get(0); TransactionDAO trans = new TransactionDAO(); String transLog = "Sucessfully sold '" + auction.getTitle() + "' (auction ID #" + auction.getId() + ") to " + bid.getBidderName() + " for " + bid.getAmountString() + " (Fee: -$" + (bid.getAmount() * 0.05) + ")."; Double amount = bid.getAmount() * 0.95; TransactionDAO transDao = new TransactionDAO(); transDao.makeTransaction(auction.getSellerId(), transLog, amount); String oldStatus = auction.getStatus(); auction.setModerateStatus(2); auction.setBuyerConfirm(""); if (this.update(auction)) { result = result + "- Auction ID #" + auction.getId() + " ('" + auction.getTitle() + "') has been sucessfully processed! [Status changed: " + oldStatus + " -> " + auction.getStatus() + "]<br>"; } else { result = result + "- Auction ID #" + auction.getId() + " ('" + auction.getTitle() + "') has failed to be processed properly!<br>"; } } } } //System.out.println(result); return result; } catch (SQLException ex) { Logger.getLogger(AuctionDAO.class.getName()).log(Level.SEVERE, null, ex); String result = "Something went wrong during the system processing auctions. The process was cancelled!"; System.out.println(result); return result; } }