List of usage examples for org.joda.time DateTime hourOfDay
public Property hourOfDay()
From source file:ch.icclab.cyclops.services.iaas.cloudstack.client.CloudStackScheduler.java
License:Open Source License
/** * Compute difference between now and closest full hour * * @return time in milliseconds//from w w w .j a va 2 s . c o m */ private long getSecondsToFullHour() { DateTime now = new DateTime(DateTimeZone.UTC); DateTime hour = now.hourOfDay().roundCeilingCopy(); // return difference in milliseconds return new Duration(now, hour).getMillis(); }
From source file:com.addthis.hydra.task.source.AbstractPersistentStreamSource.java
License:Apache License
/** */ private String replaceDateElements(DateTime time, String template) { template = template.replace("{YY}", time.year().getAsString()); template = template.replace("{Y}", getTwoDigit(time.year().get())); template = template.replace("{M}", getTwoDigit(time.monthOfYear().get())); template = template.replace("{D}", getTwoDigit(time.dayOfMonth().get())); template = template.replace("{H}", getTwoDigit(time.hourOfDay().get())); if (log.isDebugEnabled()) { log.debug("template=" + template); }//from w ww .j a va 2s . c o m return template; }
From source file:com.alliander.osgp.webdevicesimulator.service.OslpChannelHandler.java
License:Open Source License
private static DateTime correctUsageUntilDate(final DateTime dateTimeUntil, final HistoryTermType termType) { final DateTime now = new DateTime(); if (dateTimeUntil.isAfter(now)) { if (termType == HistoryTermType.Short) { return now.hourOfDay().roundCeilingCopy(); } else {/*from w w w .j a v a 2 s . c o m*/ return now.withZone(localTimeZone).dayOfWeek().roundCeilingCopy().withZone(DateTimeZone.UTC); } } return dateTimeUntil; }
From source file:com.chiorichan.plugin.lua.api.OSAPI.java
License:Mozilla Public License
@Override void initialize() { // Push a couple of functions that override original Lua API functions or // that add new functionality to it. lua.getGlobal("os"); // Custom os.clock() implementation returning the time the computer has // been actively running, instead of the native library... lua.pushJavaFunction(new JavaFunction() { @Override/*from ww w . j a v a2 s. co m*/ public int invoke(LuaState lua) { lua.pushNumber(System.currentTimeMillis()); return 1; } }); lua.setField(-2, "clock"); lua.pushJavaFunction(new JavaFunction() { @Override public int invoke(LuaState lua) { String format = lua.getTop() > 0 && lua.isString(1) ? lua.toString(1) : "%d/%m/%y %H:%M:%S"; long time = (long) (lua.getTop() > 1 && lua.isNumber(2) ? lua.toNumber(2) * 1000 / 60 / 60 : System.currentTimeMillis()); DateTime dt = new DateTime(time); if (format == "*t") { lua.newTable(0, 8); lua.pushInteger(dt.year().get()); lua.setField(-2, "year"); lua.pushInteger(dt.monthOfYear().get()); lua.setField(-2, "month"); lua.pushInteger(dt.dayOfMonth().get()); lua.setField(-2, "day"); lua.pushInteger(dt.hourOfDay().get()); lua.setField(-2, "hour"); lua.pushInteger(dt.minuteOfHour().get()); lua.setField(-2, "min"); lua.pushInteger(dt.secondOfMinute().get()); lua.setField(-2, "sec"); lua.pushInteger(dt.dayOfWeek().get()); lua.setField(-2, "wday"); lua.pushInteger(dt.dayOfYear().get()); lua.setField(-2, "yday"); } else lua.pushString(dt.toString(DateTimeFormat.forPattern(format))); return 1; } }); lua.setField(-2, "date"); /* * // Date formatting function. * lua.pushScalaFunction(lua => { * val format = * if (lua.getTop > 0 && lua.isString(1)) lua.toString(1) * else "%d/%m/%y %H:%M:%S" * val time = * if (lua.getTop > 1 && lua.isNumber(2)) lua.toNumber(2) * 1000 / 60 / 60 * else machine.worldTime + 5000 * * val dt = GameTimeFormatter.parse(time) * def fmt(format: String) { * if (format == "*t") { * lua.newTable(0, 8) * lua.pushInteger(dt.year) * lua.setField(-2, "year") * lua.pushInteger(dt.month) * lua.setField(-2, "month") * lua.pushInteger(dt.day) * lua.setField(-2, "day") * lua.pushInteger(dt.hour) * lua.setField(-2, "hour") * lua.pushInteger(dt.minute) * lua.setField(-2, "min") * lua.pushInteger(dt.second) * lua.setField(-2, "sec") * lua.pushInteger(dt.weekDay) * lua.setField(-2, "wday") * lua.pushInteger(dt.yearDay) * lua.setField(-2, "yday") * } * else { * lua.pushString(GameTimeFormatter.format(format, dt)) * } * } * * // Just ignore the allowed leading '!', Minecraft has no time zones... * if (format.startsWith("!")) * fmt(format.substring(1)) * else * fmt(format) * 1 * }) * lua.setField(-2, "date") * * // Return ingame time for os.time(). * lua.pushScalaFunction(lua => { * if (lua.isNoneOrNil(1)) { * // Game time is in ticks, so that each day has 24000 ticks, meaning * // one hour is game time divided by one thousand. Also, Minecraft * // starts days at 6 o'clock, versus the 1 o'clock of timestamps so we * // add those five hours. Thus: * // timestamp = (time + 5000) * 60[kh] * 60[km] / 1000[s] * lua.pushNumber((machine.worldTime + 5000) * 60 * 60 / 1000) * } * else { * def getField(key: String, d: Int) = { * lua.getField(-1, key) * val res = lua.toIntegerX(-1) * lua.pop(1) * if (res == null) * if (d < 0) throw new Exception("field '" + key + "' missing in date table") * else d * else res: Int * } * * lua.checkType(1, LuaType.TABLE) * lua.setTop(1) * * val sec = getField("sec", 0) * val min = getField("min", 0) * val hour = getField("hour", 12) * val mday = getField("day", -1) * val mon = getField("month", -1) * val year = getField("year", -1) * * GameTimeFormatter.mktime(year, mon, mday, hour, min, sec) match { * case Some(time) => lua.pushNumber(time) * case _ => lua.pushNil() * } * } * 1 * }) * lua.setField(-2, "time") */ // Pop the os table. lua.pop(1); }
From source file:com.enitalk.controllers.bots.EniWordController.java
public void runEniword() { try {/*from www . ja va 2 s . c om*/ mongo.updateMulti(Query.query(Criteria.where("eniword.nextPing").exists(false)), new Update() .set("eniword.nextPing", new DateTime().minusSeconds(10).toDate()).set("eniword.points", 300), "leads"); Criteria d = Criteria.where("eniword.nextPing").lte(new Date()); Criteria cal = Criteria.where("calendar").exists(true); Criteria unsubscribed = Criteria.where("eniword.disabled").exists(false); Query q = Query.query(Criteria.where("eniword.points").gt(0).andOperator(d, cal, unsubscribed)); q.fields().exclude("_id").include("dest").include("eniword").include("calendar"); List<HashMap> acolates = mongo.find(q, HashMap.class, "leads"); ArrayNode leads = jackson.convertValue(acolates, ArrayNode.class); Iterator<JsonNode> els = leads.iterator(); while (els.hasNext()) { JsonNode el = els.next(); String tz = el.at("/calendar/timeZone").asText(); DateTime now = new DateTime(DateTimeZone.forID(tz)); if (now.hourOfDay().get() < 9 || now.getHourOfDay() > 20) { logger.info("Too late to bother {}", el); mongo.updateFirst(Query.query(Criteria.where("dest.sendTo").is(el.at("/dest/sendTo").asLong())), new Update().set("eniword.nextPing", new DateTime().plusHours(1).toDate()), "leads"); return; } mongo.updateFirst(Query.query(Criteria.where("dest.sendTo").is(el.at("/dest/sendTo").asLong())), new Update().set("eniword.nextPing", new DateTime().plusSeconds(60 * 40).toDate()), "leads"); rabbit.send("eniwords", MessageBuilder.withBody(jackson.writeValueAsBytes(el)).build()); } } catch (Exception e) { logger.error(ExceptionUtils.getFullStackTrace(e)); } }
From source file:com.microsoft.office365.snippetapp.Snippets.CalendarSnippets.java
License:MIT License
/** * Creates a recurring event. This snippet will create an event that recurs * every Tuesday and Thursday from 1PM to 2PM. You can modify this snippet * to work with other recurrence patterns. * * @param subject The subject of the event * @param itemBodyHtml The body of the event as HTML * @param attendees A list of attendee email addresses * @return String The id of the created event *//* w w w.jav a2s . c o m*/ public String createRecurringCalendarEvent(String subject, String itemBodyHtml, List<String> attendees) throws ExecutionException, InterruptedException { //Create a new Office 365 Event object Event newEvent = new Event(); newEvent.setSubject(subject); ItemBody itemBody = new ItemBody(); itemBody.setContent(itemBodyHtml); itemBody.setContentType(BodyType.HTML); newEvent.setBody(itemBody); //Set the attendee list List<Attendee> attendeeList = convertEmailStringsToAttendees(attendees); newEvent.setAttendees(attendeeList); //Set start date to the next occurring Tuesday DateTime startDate = DateTime.now(); if (startDate.getDayOfWeek() < DateTimeConstants.TUESDAY) { startDate = startDate.dayOfWeek().setCopy(DateTimeConstants.TUESDAY); } else { startDate = startDate.plusWeeks(1); startDate = startDate.dayOfWeek().setCopy(DateTimeConstants.TUESDAY); } //Set start time to 1 PM startDate = startDate.hourOfDay().setCopy(13).withMinuteOfHour(0).withSecondOfMinute(0) .withMillisOfSecond(0); //Set end time to 2 PM DateTime endDate = startDate.hourOfDay().setCopy(14); //Set start and end time on the new Event (next Tuesday 1-2PM) newEvent.setStart(startDate.toCalendar(Locale.getDefault())); newEvent.setIsAllDay(false); newEvent.setEnd(endDate.toCalendar(Locale.getDefault())); //Configure the recurrence pattern for the new event //In this case the meeting will occur every Tuesday and Thursday from 1PM to 2PM RecurrencePattern recurrencePattern = new RecurrencePattern(); List<DayOfWeek> daysMeetingRecursOn = new ArrayList(); daysMeetingRecursOn.add(DayOfWeek.Tuesday); daysMeetingRecursOn.add(DayOfWeek.Thursday); recurrencePattern.setType(RecurrencePatternType.Weekly); recurrencePattern.setDaysOfWeek(daysMeetingRecursOn); recurrencePattern.setInterval(1); //recurs every week //Create a recurring range. In this case the range does not end //and the event occurs every Tuesday and Thursday forever. RecurrenceRange recurrenceRange = new RecurrenceRange(); recurrenceRange.setType(RecurrenceRangeType.NoEnd); recurrenceRange.setStartDate(startDate.toCalendar(Locale.getDefault())); //Create a pattern of recurrence. It contains the recurrence pattern //and recurrence range created previously. PatternedRecurrence patternedRecurrence = new PatternedRecurrence(); patternedRecurrence.setPattern(recurrencePattern); patternedRecurrence.setRange(recurrenceRange); //Finally pass the patterned recurrence to the new Event object. newEvent.setRecurrence(patternedRecurrence); //Create the event and return the id return mCalendarClient.getMe().getEvents().select("ID").add(newEvent).get().getId(); }
From source file:com.ofalvai.bpinfo.util.UiUtils.java
License:Apache License
/** * Transforms the start and end timestamps into a human-friendly readable string, * with special replacements for special dates, times, and the API's strange notations. * @param context Context/*from w w w. j a v a 2 s. c om*/ * @param startTimestamp Start of the alert in seconds since the UNIX epoch * @param endTimestamp End of the alert in seconds since the UNIX epoch * @return A string in the format of [startdate] [starttime] [separator] [enddate] [endtime] */ @NonNull public static String alertDateFormatter(Context context, long startTimestamp, long endTimestamp) { DateTime startDateTime = new DateTime(startTimestamp * 1000L); DateTime endDateTime = new DateTime(endTimestamp * 1000L); LocalDate startDate = startDateTime.toLocalDate(); LocalDate endDate = endDateTime.toLocalDate(); DateTime today = new DateTime(); LocalDate todayDate = new DateTime().toLocalDate(); DateTime yesterday = today.minusDays(1); LocalDate yesterdayDate = yesterday.toLocalDate(); DateTime tomorrow = today.plusDays(1); LocalDate tomorrowDate = tomorrow.toLocalDate(); // Alert start, date part String startDateString; if (startDate.equals(todayDate)) { // Start day is today, replacing month and day with today string startDateString = context.getString(R.string.date_today) + " "; } else if (startDate.year().get() < today.year().get()) { // The start year is less than the current year, displaying the year too startDateString = Config.FORMATTER_DATE_YEAR.print(startDateTime); } else if (startDate.equals(yesterdayDate)) { startDateString = context.getString(R.string.date_yesterday) + " "; } else if (startDate.equals(tomorrowDate)) { startDateString = context.getString(R.string.date_tomorrow) + " "; } else { startDateString = Config.FORMATTER_DATE.print(startDateTime); } // Alert start, time part String startTimeString; if (startDateTime.hourOfDay().get() == 0 && startDateTime.minuteOfHour().get() == 0) { // The API marks "first departure" as 00:00 startTimeString = context.getString(R.string.date_first_departure); } else { startTimeString = Config.FORMATTER_TIME.print(startDateTime); } // Alert end, date part String endDateString; if (endTimestamp == 0) { // The API marks "until further notice" as 0 (in UNIX epoch), no need to display date // (the replacement string is displayed as the time part, not the date) endDateString = " "; } else if (endDate.year().get() > today.year().get()) { // The end year is greater than the current year, displaying the year too endDateString = Config.FORMATTER_DATE_YEAR.print(endDateTime); } else if (endDate.equals(todayDate)) { // End day is today, replacing month and day with today string endDateString = context.getString(R.string.date_today) + " "; } else if (endDate.equals(yesterdayDate)) { endDateString = context.getString(R.string.date_yesterday) + " "; } else if (endDate.equals(tomorrowDate)) { endDateString = context.getString(R.string.date_tomorrow) + " "; } else { endDateString = Config.FORMATTER_DATE.print(endDateTime); } // Alert end, time part String endTimeString; if (endTimestamp == 0) { // The API marks "until further notice" as 0 (in UNIX epoch) endTimeString = context.getString(R.string.date_until_revoke); } else if (endDateTime.hourOfDay().get() == 23 && endDateTime.minuteOfHour().get() == 59) { // The API marks "last departure" as 23:59 endTimeString = context.getString(R.string.date_last_departure); } else { endTimeString = Config.FORMATTER_TIME.print(endDateTime); } return startDateString + startTimeString + Config.DATE_SEPARATOR + endDateString + endTimeString; }
From source file:com.proofpoint.event.monitor.s3.S3EventStore.java
License:Apache License
@Override public boolean recentEventExists(String eventType, EventPredicate filter, DateTime limit) { for (URI dateBaseUri : storageSystem .listDirectoriesNewestFirst(buildS3Directory(eventStagingLocation, eventType))) { DateTime dateBucket = DATE_FORMAT.parseDateTime(getS3FileName(dateBaseUri)); for (URI hourBaseUri : storageSystem.listDirectoriesNewestFirst(dateBaseUri)) { int hour = Integer.parseInt(getS3FileName(hourBaseUri)); // The bucket may contain events up to the start of the following hour DateTime bucketDateTime = dateBucket.hourOfDay().setCopy(hour).plusHours(1); if (bucketDateTime.isBefore(limit)) { return false; }/*w w w . ja v a 2 s. com*/ for (URI eventFile : storageSystem.listObjects(hourBaseUri)) { InputStream s3Object = null; try { s3Object = storageSystem.getInputSupplier(eventFile).getInput(); Iterator<Event> eventIterator = getEventIterator(s3Object, objectMapper); while (eventIterator.hasNext()) { Event event = eventIterator.next(); if (filter.apply(event) && event.getTimestamp().isAfter(limit)) { return true; } } } catch (IOException e) { log.warn(e, "Exception while checking S3 object %s for recent event of type %s (filter %s)", eventFile, eventType, filter); } finally { Closeables.closeQuietly(s3Object); } } } } return false; }
From source file:com.qcadoo.model.internal.types.DateType.java
License:Open Source License
@Override public ValueAndError toObject(final FieldDefinition fieldDefinition, final Object value) { if (value instanceof Date) { return ValueAndError.withoutError(value); }//from w ww.java 2s . c o m try { DateTimeFormatter fmt = DateTimeFormat.forPattern(DateUtils.L_DATE_FORMAT); DateTime dt = fmt.parseDateTime(String.valueOf(value)); int year = dt.getYear(); if (year < 1500 || year > 2500) { return ValueAndError.withError("qcadooView.validate.field.error.invalidDateFormat.range"); } Date date = dt.toDate(); if (year < 2000) { Calendar c = Calendar.getInstance(); c.set(Calendar.YEAR, dt.getYear()); c.set(Calendar.MONTH, dt.getMonthOfYear() - 1); c.set(Calendar.DAY_OF_MONTH, dt.getDayOfMonth()); c.set(Calendar.HOUR_OF_DAY, dt.hourOfDay().get()); c.set(Calendar.MINUTE, dt.getMinuteOfHour()); c.set(Calendar.SECOND, dt.getSecondOfMinute()); c.set(Calendar.MILLISECOND, dt.getMillisOfSecond()); date = c.getTime(); } return ValueAndError.withoutError(date); } catch (IllegalArgumentException e) { return ValueAndError.withError("qcadooView.validate.field.error.invalidDateFormat"); } }
From source file:com.sap.dirigible.runtime.metrics.TimeUtils.java
License:Open Source License
private static DateTime dateTimeCeiling(DateTime dt, Period p) { if (p.getYears() != 0) { return dt.yearOfEra().roundCeilingCopy().minusYears(dt.getYearOfEra() % p.getYears()); } else if (p.getMonths() != 0) { return dt.monthOfYear().roundCeilingCopy().minusMonths((dt.getMonthOfYear() - 1) % p.getMonths()); } else if (p.getWeeks() != 0) { return dt.weekOfWeekyear().roundCeilingCopy().minusWeeks((dt.getWeekOfWeekyear() - 1) % p.getWeeks()); } else if (p.getDays() != 0) { return dt.dayOfMonth().roundCeilingCopy().minusDays((dt.getDayOfMonth() - 1) % p.getDays()); } else if (p.getHours() != 0) { return dt.hourOfDay().roundCeilingCopy().minusHours(dt.getHourOfDay() % p.getHours()); } else if (p.getMinutes() != 0) { return dt.minuteOfHour().roundCeilingCopy().minusMinutes(dt.getMinuteOfHour() % p.getMinutes()); } else if (p.getSeconds() != 0) { return dt.secondOfMinute().roundCeilingCopy().minusSeconds(dt.getSecondOfMinute() % p.getSeconds()); }/* w w w .j a v a 2 s. com*/ return dt.millisOfSecond().roundCeilingCopy().minusMillis(dt.getMillisOfSecond() % p.getMillis()); }