Exemplo n.º 1
0
 private DateTime ensureSameDate(
     DateTime date,
     int years,
     int monthsOfYear,
     int dayOfMonth,
     int hoursOfDay,
     int minutesOfHour,
     int secondsOfMinute,
     DateTimeZone timeZone) {
   if (date.getSecondOfMinute() != secondsOfMinute) {
     date = date.plusSeconds(secondsOfMinute - date.getSecondOfMinute());
   }
   if (date.getMinuteOfHour() != minutesOfHour) {
     date = date.plusMinutes(minutesOfHour - date.getMinuteOfHour());
   }
   if (date.getHourOfDay() != hoursOfDay) {
     date = date.plusHours(hoursOfDay - date.getHourOfDay());
   }
   if (date.getDayOfMonth() != dayOfMonth) {
     date = date.plusDays(dayOfMonth - date.getDayOfMonth());
   }
   if (date.getMonthOfYear() != monthsOfYear) {
     date = date.plusMonths(monthsOfYear - date.getMonthOfYear());
   }
   if (date.getYear() != years) {
     date = date.plusYears(years - date.getYear());
   }
   return date;
 }
  /**
   * Samples a data point from the Cars Per Hour model, using the given timestamp
   *
   * @param timestamp Timestamp to simulate traffic data for. Specify in milliseconds since epoch.
   *     Use UTC!
   * @return Simulated data for Cars Per Hour based on the model
   * @throws Exception
   */
  public TrafficData sampleCarsPerHourModel(long timestamp) throws Exception {
    // Verify we have a traffic model for this segment
    if (carsPerHour == null) {
      generateModel();
    }

    DateTime time = new DateTime(timestamp, DateTimeZone.UTC);
    int hour = time.getHourOfDay();
    TrafficData traffic = null;

    // Add cars-per-hour data
    if (carsPerHour.containsKey(hour)) {
      // We have traffic data for the hour, sample it.
      Double sample = carsPerHour.get(hour).sample(1)[0];
      if (sample <= 0) {
        traffic = new TrafficData(fromNode, toNode, time.getMillis() / 1000, "CARS_PER_HOUR", 0.0);
      } else {
        traffic =
            new TrafficData(
                fromNode,
                toNode,
                time.getMillis() / 1000,
                "CARS_PER_HOUR",
                (double) Math.round(sample));
      }
    } else {
      // TODO: See if we have the previous hour and the next hour and interpolate the data if we do
      // For now, just assume that there is a random number between 0-100 cars, since all
      // measurements at that hour had the same amount of cars.
      // NOTE: Even though it says max is 101, it's actually 100, since it's exclusive for the top
      // bound.
      traffic =
          new TrafficData(
              fromNode,
              toNode,
              time.getMillis() / 1000,
              "CARS_PER_HOUR",
              (double) ThreadLocalRandom.current().nextInt(0, 101));
    }

    if (traffic != null && traffic.isValid()) {
      // Traffic has data
      return traffic;
    } else {
      // Traffic didn't have any data
      throw new Exception(
          String.format(
              "No traffic model for the given timestamp: %d (Hour: %d)",
              time.getMillis(), time.getHourOfDay()));
    }
  }
Exemplo n.º 3
0
 private Integer hasTime(DateTime proposedDiscussed) {
   if (proposedDiscussed.getHourOfDay() == 0 && proposedDiscussed.getMinuteOfHour() == 0) {
     return 0;
   } else {
     return 1;
   }
 }
Exemplo n.º 4
0
  public static Article createArticleFromJson(JSONObject json)
      throws JSONException, ParseException {
    String title = json.getString("title");
    String date = json.getString("date");
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    Date utilDate = df.parse(date);
    DateTime jodaDate = new DateTime(utilDate);

    int hourOfDay = jodaDate.getHourOfDay();
    int dayOfMonth = jodaDate.getDayOfMonth();
    int minuteOfHour = jodaDate.getMinuteOfHour();
    int monthOfYear = jodaDate.getMonthOfYear();

    String author = json.getString("author");
    String imageURL = json.getString("imageurl");
    String thumbnailURL = json.getString("thumbnailurl");
    String postedString = json.getString("posted");
    boolean posted = postedString.equals("yes");

    String body = json.getString("body");

    return new Article(
        title,
        dayOfMonth,
        hourOfDay,
        minuteOfHour,
        author,
        imageURL,
        thumbnailURL,
        posted,
        body,
        monthOfYear);
  }
  private void printStat(LiveStatistics ls) {
    long ms = ls.getTimeperiod() * 15000;
    DateTime time = new DateTime(ms);

    StringBuilder sb = new StringBuilder();
    sb.append(time.getDayOfMonth())
        .append(".")
        .append(time.getMonthOfYear())
        .append(".")
        .append(time.getYear());
    sb.append(" ")
        .append(time.getHourOfDay())
        .append(":")
        .append(time.getMinuteOfHour())
        .append(":")
        .append(time.getSecondOfMinute());

    System.out.println(
        ls.getTimeperiod()
            + ";"
            + ls.getAccountName()
            + "; date: "
            + sb.toString()
            + " value: "
            + ls.getValue()
            + " unitType: "
            + ls.getUnitType()
            + " valueType: "
            + ls.getValueType());
  }
 public SUTime.Temporal apply(String text) {
   // TODO: TIMEZONE?
   DateTime dateTime = null;
   try {
     dateTime = formatter.parseDateTime(text);
   } catch (org.joda.time.IllegalFieldValueException e) {
     logger.warning(
         "WARNING: Invalid temporal \""
             + text
             + "\" ("
             + e.getMessage()
             + "). Skipping and continuing...");
     return null;
   }
   assert (dateTime != null);
   if (hasDate && hasTime) {
     return new SUTime.GroundedTime(dateTime);
     //        return new SUTime.IsoDateTime( new SUTime.IsoTime(dateTime.getHourOfDay(),
     // dateTime.getMinuteOfHour(), dateTime.getSecondOfMinute());
     //        Date d = new SUTime.IsoDate(dateTime.getYear(), dateTime.getMonthOfYear(),
     // dateTime.getDayOfMonth()) );
   } else if (hasTime) {
     // TODO: Millisecs?
     return new SUTime.IsoTime(
         dateTime.getHourOfDay(), dateTime.getMinuteOfHour(), dateTime.getSecondOfMinute());
   } else if (hasDate) {
     return new SUTime.IsoDate(
         dateTime.getYear(), dateTime.getMonthOfYear(), dateTime.getDayOfMonth());
   } else {
     return null;
   }
 }
Exemplo n.º 7
0
    @Specialization
    public RubyBasicObject timeDecompose(VirtualFrame frame, RubyTime time) {
      CompilerDirectives.transferToInterpreter();
      final DateTime dateTime = time.getDateTime();
      final int sec = dateTime.getSecondOfMinute();
      final int min = dateTime.getMinuteOfHour();
      final int hour = dateTime.getHourOfDay();
      final int day = dateTime.getDayOfMonth();
      final int month = dateTime.getMonthOfYear();
      final int year = dateTime.getYear();

      int wday = dateTime.getDayOfWeek();

      if (wday == 7) {
        wday = 0;
      }

      final int yday = dateTime.getDayOfYear();
      final boolean isdst = false;

      final String envTimeZoneString = readTimeZoneNode.executeRubyString(frame).toString();
      String zoneString = org.jruby.RubyTime.zoneHelper(envTimeZoneString, dateTime, false);
      Object zone;
      if (zoneString.matches(".*-\\d+")) {
        zone = nil();
      } else {
        zone = createString(zoneString);
      }

      final Object[] decomposed =
          new Object[] {sec, min, hour, day, month, year, wday, yday, isdst, zone};
      return createArray(decomposed, decomposed.length);
    }
Exemplo n.º 8
0
  public RubyObject mdump() {
    RubyTime obj = this;
    DateTime dateTime = obj.dt.toDateTime(DateTimeZone.UTC);
    byte dumpValue[] = new byte[8];

    int pe =
        0x1 << 31
            | ((obj.gmt().isTrue()) ? 0x1 : 0x0) << 30
            | (dateTime.getYear() - 1900) << 14
            | (dateTime.getMonthOfYear() - 1) << 10
            | dateTime.getDayOfMonth() << 5
            | dateTime.getHourOfDay();
    int se =
        dateTime.getMinuteOfHour() << 26
            | dateTime.getSecondOfMinute() << 20
            | (dateTime.getMillisOfSecond() * 1000 + (int) usec); // dump usec, not msec

    for (int i = 0; i < 4; i++) {
      dumpValue[i] = (byte) (pe & 0xFF);
      pe >>>= 8;
    }
    for (int i = 4; i < 8; i++) {
      dumpValue[i] = (byte) (se & 0xFF);
      se >>>= 8;
    }
    return RubyString.newString(obj.getRuntime(), new ByteList(dumpValue));
  }
Exemplo n.º 9
0
 public void setDateTime(DateTime time) {
   month.setText(strMonth(time.getMonthOfYear()));
   year.setText("" + time.getYear());
   day.setText("" + time.getDayOfMonth());
   day.setFont(new Font("Calibri", Font.BOLD, 22));
   t.setText(formatTime(time.getHourOfDay(), time.getMinuteOfHour()));
 }
Exemplo n.º 10
0
  public DateTimeView(DateTime time) {
    super();
    this.time = time;
    Font f = new Font("Monospaced", Font.BOLD, 13);
    Color c = new Color(44, 68, 152);
    month = new JLabel(strMonth(time.getMonthOfYear()));
    month.setFont(f);
    month.setForeground(c);
    year = new JLabel("" + time.getYear());
    year.setFont(f);
    year.setForeground(c);
    day = new JLabel("" + time.getDayOfMonth());
    day.setFont(new Font("Calibri", Font.BOLD, 26));
    day.setForeground(new Color(126, 148, 227));
    t = new JLabel(formatTime(time.getHourOfDay(), time.getMinuteOfHour()));
    t.setFont(f);
    t.setForeground(c);

    JPanel topPanel = new JPanel();
    topPanel.setLayout(new FlowLayout());
    topPanel.add(month);
    topPanel.add(year);

    this.setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
    topPanel.setAlignmentX(Component.CENTER_ALIGNMENT);
    this.add(topPanel);
    this.add(Box.createVerticalStrut(3));
    day.setAlignmentX(Component.CENTER_ALIGNMENT);
    this.add(day);
    t.setAlignmentX(Component.CENTER_ALIGNMENT);
    this.add(Box.createVerticalStrut(3));
    this.add(t);
    this.setBorder(BorderFactory.createRaisedBevelBorder());
  }
Exemplo n.º 11
0
  private String calculateDayPath(String name, DateTime base) {
    StringBuilder builder = new StringBuilder();

    builder.append(getWritePath());
    builder.append(File.separatorChar);
    builder.append(name);
    builder.append(File.separatorChar);
    builder.append(base.getYear());
    builder.append(File.separatorChar);
    builder.append(base.getMonthOfYear());
    builder.append(File.separatorChar);
    builder.append(base.getDayOfMonth());
    builder.append(File.separatorChar);

    String path = builder.toString();

    (new File(path)).mkdirs();

    builder.append(base.getHourOfDay());
    builder.append(".txt");

    path = builder.toString();

    return path;
  }
 /** Issue #24: next execution not properly calculated */
 @Test
 public void testTimeShiftingProperlyDone() throws Exception {
   ExecutionTime executionTime = ExecutionTime.forCron(quartzCronParser.parse("0 0/10 22 * * *"));
   DateTime nextExecution =
       executionTime.nextExecution(DateTime.now().withHourOfDay(15).withMinuteOfHour(27));
   assertEquals(22, nextExecution.getHourOfDay());
   assertEquals(0, nextExecution.getMinuteOfHour());
 }
 private DateTime truncateToSeconds(DateTime dateTime) {
   return new DateTime(
       dateTime.getYear(),
       dateTime.getMonthOfYear(),
       dateTime.getDayOfMonth(),
       dateTime.getHourOfDay(),
       dateTime.getMinuteOfHour(),
       dateTime.getSecondOfMinute());
 }
Exemplo n.º 14
0
  @Test
  @RegressionTest({
    "https://issues.jboss.org/browse/RF-9837",
    "https://issues.jboss.org/browse/RF-10085"
  })
  public void testDefaultTime() {
    final String t = "06:06";
    calendarAttributes.set(CalendarAttributes.defaultTime, t);
    setCurrentDateWithCalendarsTodayButtonAction.perform();
    String text = calendar.openPopup().getFooterControls().getTimeEditorOpenerElement().getText();
    assertTrue(text.equals(t), "Default time");

    // another check in time editor
    TimeEditor timeEditor = calendar.openPopup().getFooterControls().openTimeEditor();
    DateTime setTime = timeEditor.getTime();
    DateTime reference = todayMidday.withHourOfDay(6).withMinuteOfHour(6);
    assertEquals(setTime.getHourOfDay(), reference.getHourOfDay());
    assertEquals(setTime.getMinuteOfHour(), reference.getMinuteOfHour());
  }
  private void calculateDatePart() {
    final DateTime dateTime = new DateTime(getFile().lastModified());

    final int year = dateTime.getYearOfCentury();
    final String month = Integer.toHexString(dateTime.getMonthOfYear());
    final String day = Integer.toString(dateTime.getDayOfMonth(), 32);
    final String hour = Integer.toString(dateTime.getHourOfDay(), 25);

    datePart = year + month + day + hour;
  }
  /**
   * Test for issue #18
   *
   * @throws Exception
   */
  @Test
  public void testHourlyIntervalTimeFromLastExecution() throws Exception {
    DateTime now = DateTime.now();
    DateTime previousHour = now.minusHours(1);
    String quartzCronExpression = String.format("0 0 %s * * ?", previousHour.getHourOfDay());
    ExecutionTime executionTime =
        ExecutionTime.forCron(quartzCronParser.parse(quartzCronExpression));

    assertTrue(executionTime.timeFromLastExecution(now).getStandardMinutes() <= 120);
  }
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
      // Use the current time as the default values for the picker
      DateTime date = new DateTime();
      int hour = date.getHourOfDay();
      int minute = date.getMinuteOfHour();

      // Create a new instance of TimePickerDialog and return it
      return new TimePickerDialog(
          getActivity(), this, hour, minute, DateFormat.is24HourFormat(getActivity()));
    }
Exemplo n.º 18
0
 @Test
 @Ignore
 public void testRead() {
   Patient patient = entityManager.find(Patient.class, 3);
   assertTrue(patient.getAppointments().size() > 0);
   DateTime st = patient.getAppointments().iterator().next().getStart();
   assertEquals(2013, st.getYear());
   assertEquals(2, st.getMonthOfYear());
   assertEquals(18, st.getDayOfMonth());
   assertEquals(8, st.getHourOfDay());
 }
Exemplo n.º 19
0
 /**
  * We need the number of days rather than the number of elapsed milliseconds divided by the number
  * in a day - timezone changes ete... To avoid confusion about what constitutes a full day we
  * count the number of lunchtimes (noon).
  *
  * @param start
  * @param end
  * @return
  */
 private int countDays(DateTime start, DateTime end) {
   int count = 0;
   Assert.assertEquals(start.getHourOfDay(), 0);
   Assert.assertEquals(start.getMinuteOfHour(), 0);
   start = start.plusHours(12);
   while (start.isBefore(end)) {
     count++;
     start = start.plusDays(1);
   }
   return count;
 }
Exemplo n.º 20
0
  private boolean validate() {
    if (creator.getInvite() == null) {
      return false;
    } else {
      if (creator.getInvite().date == 0l) {
        String message = "";
        if (creator.getInvite().time == 0l || TextUtils.isEmpty(inviteTitle.getText())) {
          message = getString(R.string.all_fields_error);
        } else {
          message = String.format(getString(R.string.one_field_error), "date");
        }
        Snackbar.make(inviteDetailsCard, message, Snackbar.LENGTH_LONG).show();
        return false;
      }
      if (creator.getInvite().time == 0l) {
        String message = "";
        if (creator.getInvite().date == 0l || TextUtils.isEmpty(inviteTitle.getText())) {
          message = getString(R.string.all_fields_error);
        } else {
          message = String.format(getString(R.string.one_field_error), "time");
        }
        Snackbar.make(inviteDetailsCard, message, Snackbar.LENGTH_LONG).show();
        return false;
      }
      if (TextUtils.isEmpty(inviteTitle.getText())) {
        String message = "";
        if (creator.getInvite().time == 0l || creator.getInvite().date == 0l) {
          message = getString(R.string.all_fields_error);
        } else {
          message = String.format(getString(R.string.one_field_error), "title");
        }
        Snackbar.make(inviteDetailsCard, message, Snackbar.LENGTH_LONG).show();
        return false;
      }

      DateTime time = new DateTime().withMillis(creator.getInvite().time);
      DateTime date = new DateTime().withMillis(creator.getInvite().date);
      DateTime when =
          new DateTime()
              .withYear(date.getYear())
              .withMonthOfYear(date.getMonthOfYear())
              .withDayOfMonth(date.getDayOfMonth())
              .withHourOfDay(time.getHourOfDay())
              .withMinuteOfHour(time.getMinuteOfHour());

      if (when.isBeforeNow()) {
        Snackbar.make(inviteDetailsCard, getString(R.string.wrong_datetime), Snackbar.LENGTH_LONG)
            .show();
        return false;
      }
    }
    return true;
  }
Exemplo n.º 21
0
 public void testCreateNewUtcDate() {
   DateTime utc = now.toDateTime(DateTimeZone.UTC);
   Date actual =
       newDateUtc(
           utc.getYear(),
           utc.getMonthOfYear(),
           utc.getDayOfMonth(),
           utc.getHourOfDay(),
           utc.getMinuteOfHour(),
           utc.getSecondOfMinute());
   assertEquals(utc.getMillis(), actual.getTime());
 }
Exemplo n.º 22
0
 private static LocalDateTime parseJavaLocalDateTimeUI(String str) {
   // First parse to Joda DateTime for timezone calculation
   DateTime dateTime = DTF.parseDateTime(str);
   // Then create LocalDateTime from Joda DateTime and return it
   return LocalDateTime.of(
       dateTime.getYear(),
       dateTime.getMonthOfYear(),
       dateTime.getDayOfMonth(),
       dateTime.getHourOfDay(),
       dateTime.getMinuteOfHour(),
       dateTime.getSecondOfMinute());
 }
  @Test
  public void shouldGetPreviousFireTime() throws InterruptedException {
    try {
      fakeNow(new DateTime());

      Map<String, Object> params = new HashMap<>();
      MotechEvent event = new MotechEvent("test_event", params);
      final String jobId = id("jobId");
      params.put(MotechSchedulerService.JOB_ID_KEY, jobId);
      DateTime now = new DateTime();
      StringBuilder cron = new StringBuilder();
      cron.append(now.getSecondOfMinute()).append(" ").append(now.getMinuteOfHour()).append(" ");
      cron.append(now.getHourOfDay()).append(" * * ?");
      schedulerService.scheduleJob(new CronSchedulableJob(event, cron.toString()));
      Thread.sleep(1000);
      DateTime dateTime = schedulerService.getPreviousFireDate(new CronJobId(event));
      assertEquals(dateTime.getHourOfDay(), now.getHourOfDay());
      assertEquals(dateTime.getMinuteOfHour(), now.getMinuteOfHour());
      assertEquals(dateTime.getSecondOfMinute(), now.getSecondOfMinute());
    } finally {
      stopFakingTime();
    }
  }
Exemplo n.º 24
0
 private static Object parseDateTime(DateTime val, String toClass) {
   switch (toClass) {
     case "org.joda.time.DateTime":
       return val;
     case "java.util.Date":
       return val.toDate();
     case "org.joda.time.LocalDate":
       return val.toLocalDate();
     case "org.motechproject.commons.date.model.Time":
       return new Time(val.getHourOfDay(), val.getMinuteOfHour());
     default:
       return null;
   }
 }
 @Override
 protected Function<Transaction, TransactionAggregationByCountry> mapFunction() {
   return transaction -> {
     final DateTime time = transaction.getReceivedTime().withZone(MtpConstants.DEFAULT_TIME_ZONE);
     return new TransactionAggregationByCountry(
         transaction.getOriginatingCountry(),
         time.getYear(),
         time.getMonthOfYear(),
         time.getDayOfMonth(),
         time.getHourOfDay(),
         1,
         transaction.getAmountPoints());
   };
 }
 /**
  * Test for issue #9 https://github.com/jmrozanec/cron-utils/issues/9 Reported case: If you write
  * a cron expression that contains a month or day of week, nextExection() ignores it. Expected:
  * should not ignore month or day of week field
  */
 @Test
 public void testDoesNotIgnoreMonthOrDayOfWeek() {
   CronDefinition cronDefinition = CronDefinitionBuilder.instanceDefinitionFor(CronType.QUARTZ);
   CronParser cronParser = new CronParser(cronDefinition);
   // seconds, minutes, hours, dayOfMonth, month, dayOfWeek
   ExecutionTime executionTime = ExecutionTime.forCron(cronParser.parse("0 11 11 11 11 ?"));
   DateTime now = new DateTime(2015, 4, 15, 0, 0, 0);
   DateTime whenToExecuteNext = executionTime.nextExecution(now);
   assertEquals(2015, whenToExecuteNext.getYear());
   assertEquals(11, whenToExecuteNext.getMonthOfYear());
   assertEquals(11, whenToExecuteNext.getDayOfMonth());
   assertEquals(11, whenToExecuteNext.getHourOfDay());
   assertEquals(11, whenToExecuteNext.getMinuteOfHour());
   assertEquals(0, whenToExecuteNext.getSecondOfMinute());
 }
Exemplo n.º 27
0
  @Test
  public void totalDosesWhenEndTimeIsNull() {
    DateTime now = new DateTime(2011, 10, 3, 10, 0, 0, 0);
    final DateTime dosageStartTime = now.minusDays(1);
    Dosage dosage =
        new Dosage(
            new DosageResponse(
                "dosage_id",
                new Time(dosageStartTime.getHourOfDay(), dosageStartTime.getMinuteOfHour()),
                dosageStartTime.toLocalDate(),
                null,
                null,
                null));

    assertEquals(2, dosage.getDosesBetween(dosageStartTime.toLocalDate(), now));
  }
    private String toTime(DateTime dateTime) {
      int hour = dateTime.getHourOfDay();
      int min = dateTime.getMinuteOfHour();
      StringBuilder sb = new StringBuilder();

      if (hour < 10) {
        sb.append("0");
      }
      sb.append(String.valueOf(hour));
      sb.append(":");
      if (min == 0) {
        sb.append("0");
      }
      sb.append(String.valueOf(min));
      return sb.toString();
    }
Exemplo n.º 29
0
  @Test
  public void totalDosesWhenDosageStartDateEqualsDosageEndDate() {
    DateTime now = new DateTime(2011, 10, 2, 10, 0, 0, 0);
    final DateTime dosageStartTime = now;
    final DateTime dosageEndTime = dosageStartTime;
    Dosage dosage =
        new Dosage(
            new DosageResponse(
                "dosage_id",
                new Time(dosageStartTime.getHourOfDay(), dosageStartTime.getMinuteOfHour()),
                dosageStartTime.toLocalDate(),
                dosageEndTime.toLocalDate(),
                null,
                null));

    assertEquals(1, dosage.getDosesBetween(dosageStartTime.toLocalDate(), dosageEndTime));
  }
Exemplo n.º 30
0
  @Test
  public void shouldIncludeBothFromAndToDate_WhenGettingNumberOfDoses() {
    DateTime now = new DateTime(2011, 10, 3, 10, 0, 0, 0);
    final DateTime dosageStartTime = now.minusWeeks(1);
    final DateTime dosageEndTime = now.plusDays(1);
    Dosage dosage =
        new Dosage(
            new DosageResponse(
                "dosage_id",
                new Time(dosageStartTime.getHourOfDay(), dosageStartTime.getMinuteOfHour()),
                dosageStartTime.toLocalDate(),
                dosageEndTime.toLocalDate(),
                null,
                null));

    assertEquals(8, dosage.getDosesBetween(now.minusWeeks(1).toLocalDate(), now));
  }