java.util.Date

Here are the examples of the java api class java.util.Date taken from open source projects.

1. ParseTimestampTest#testGitLikeStrings()

Project: geogig
Source File: ParseTimestampTest.java
View license
@Test
public void testGitLikeStrings() throws ParseException {
    Date today = format.parse("1972-10-10 00:00:00");
    Date yesterday = format.parse("1972-10-09 00:00:00");
    Date aMinuteAgo = format.parse("1972-10-10 10:09:10");
    Date tenMinutesAgo = format.parse("1972-10-10 10:00:10");
    Date tenHoursTenMinutesAgo = format.parse("1972-10-10 00:00:10");
    Date aWeekAgo = format.parse("1972-10-03 10:10:10");
    Date actual;
    actual = new Date(command.setString("today").call());
    assertEquals(today, actual);
    actual = new Date(command.setString("yesterday").call());
    assertEquals(yesterday, actual);
    actual = new Date(command.setString("1.minute.ago").call());
    assertEquals(aMinuteAgo, actual);
    actual = new Date(command.setString("10.minutes.ago").call());
    assertEquals(tenMinutesAgo, actual);
    actual = new Date(command.setString("10.MINUTES.AGO").call());
    assertEquals(tenMinutesAgo, actual);
    actual = new Date(command.setString("10.hours.10.minutes.ago").call());
    assertEquals(tenHoursTenMinutesAgo, actual);
    actual = new Date(command.setString("1.week.ago").call());
    assertEquals(aWeekAgo, actual);
}

2. AlbianDateTime#dateAddSeconds()

Project: Albianj2
Source File: AlbianDateTime.java
View license
@SuppressWarnings("deprecation")
public static Date dateAddSeconds(int year, int month, int day, long second) {
    Date dt = new Date();
    dt.setYear(year - 1900);
    dt.setMonth(month - 1);
    dt.setDate(day);
    dt.setHours(0);
    dt.setMinutes(0);
    dt.setSeconds(0);
    Calendar rightNow = Calendar.getInstance();
    rightNow.setTime(dt);
    rightNow.add(Calendar.SECOND, (int) second);
    Date dt1 = rightNow.getTime();
    return dt1;
}

3. VersionInfoTest#testConvertVersionNameToAge()

Project: fitnesse
Source File: VersionInfoTest.java
View license
@Test
public void testConvertVersionNameToAge() throws Exception {
    Date now = new GregorianCalendar(2003, 0, 1, 00, 00, 01).getTime();
    Date tenSeconds = new GregorianCalendar(2003, 0, 1, 00, 00, 11).getTime();
    Date twoMinutes = new GregorianCalendar(2003, 0, 1, 00, 02, 01).getTime();
    Date fiftyNineSecs = new GregorianCalendar(2003, 0, 1, 00, 01, 00).getTime();
    Date oneHour = new GregorianCalendar(2003, 0, 1, 01, 00, 01).getTime();
    Date fiveDays = new GregorianCalendar(2003, 0, 6, 00, 00, 01).getTime();
    Date years = new GregorianCalendar(2024, 0, 1, 00, 00, 01).getTime();
    assertEquals("10 seconds", VersionInfo.howLongAgoString(now, tenSeconds));
    assertEquals("2 minutes", VersionInfo.howLongAgoString(now, twoMinutes));
    assertEquals("59 seconds", VersionInfo.howLongAgoString(now, fiftyNineSecs));
    assertEquals("1 hour", VersionInfo.howLongAgoString(now, oneHour));
    assertEquals("5 days", VersionInfo.howLongAgoString(now, fiveDays));
    assertEquals("21 years", VersionInfo.howLongAgoString(now, years));
}

4. Confirm4e#bodyValuesMatch()

Project: flex-blazeds
Source File: Confirm4e.java
View license
protected boolean bodyValuesMatch(Object o1, Object o2) {
    boolean match = super.bodyValuesMatch(o1, o2);
    // Also check that by-reference serialization of dates restored
    // the pointers to the original date...
    Object list1 = o1;
    Object list2 = o2;
    Date d11 = (Date) getFromList(list1, 0);
    Date d12 = (Date) getFromList(list1, 1);
    Date d13 = (Date) getFromList(list1, 2);
    if (d11 != d12 || d12 != d13)
        return false;
    Date d21 = (Date) getFromList(list2, 0);
    Date d22 = (Date) getFromList(list2, 1);
    Date d23 = (Date) getFromList(list2, 2);
    if (d21 != d22 || d22 != d23)
        return false;
    return match;
}

5. ValueMetaTest#testCompareDatesNormalStorageData()

Project: pentaho-kettle
Source File: ValueMetaTest.java
View license
public void testCompareDatesNormalStorageData() throws Exception {
    Date date1 = new Date();
    Date date2 = new Date(date1.getTime() + 3600);
    Date date3 = new Date(date1.getTime() - 3600);
    Date date4 = new Date(date1.getTime());
    Date date5 = null;
    Date date6 = null;
    ValueMetaInterface one = new ValueMeta("one", ValueMetaInterface.TYPE_DATE);
    ValueMetaInterface two = new ValueMeta("two", ValueMetaInterface.TYPE_DATE);
    assertTrue(one.compare(date1, date2) < 0);
    assertTrue(one.compare(date1, date3) > 0);
    assertTrue(one.compare(date1, date4) == 0);
    assertTrue(one.compare(date1, date5) != 0);
    assertTrue(one.compare(date5, date6) == 0);
    assertTrue(one.compare(date1, two, date2) < 0);
    assertTrue(one.compare(date1, two, date3) > 0);
    assertTrue(one.compare(date1, two, date4) == 0);
    assertTrue(one.compare(date1, two, date5) != 0);
    assertTrue(one.compare(date5, two, date6) == 0);
}

6. CorresponDaoImplTest#createFindCondition3()

View license
/**
     * testFindCondition3??????????????
     * ???CreatedOn?From?To??UpdatedOn?From?To??DeadlineForReply?From?To?
     * @return ??????????
     */
private SearchCorresponCondition createFindCondition3() {
    SearchCorresponCondition condition = new SearchCorresponCondition();
    condition.setProjectId("0-5000-2");
    condition.setUserId("ZZA01");
    condition.setPageNo(1);
    condition.setPageRowNum(20);
    condition.setSort("id");
    condition.setAscending(true);
    // SystemAdmin
    condition.setSystemAdmin(true);
    Date date1 = new GregorianCalendar(2009, 3, 1).getTime();
    Date date2 = new GregorianCalendar(2009, 3, 10).getTime();
    Date date3 = new GregorianCalendar(2009, 3, 1).getTime();
    Date date4 = new GregorianCalendar(2009, 3, 10).getTime();
    Date date5 = new GregorianCalendar(2009, 3, 7).getTime();
    Date date6 = new GregorianCalendar(2009, 3, 16).getTime();
    condition.setFromCreatedOn(date1);
    condition.setToCreatedOn(date2);
    condition.setFromIssuedOn(date3);
    condition.setToIssuedOn(date4);
    condition.setFromDeadlineForReply(date5);
    condition.setToDeadlineForReply(date6);
    return condition;
}

7. TaskFormActivity#addReminder()

View license
@OnClick(R.id.add_reminder_button)
public void addReminder() {
    Date startDate = new Date(startDateListener.getCalendar().getTimeInMillis());
    Date time = startDate;
    String reminderTimeString = newRemindersEditText.getText().toString();
    if (reminderTimeString.isEmpty())
        return;
    String[] reminderTimeSplit = reminderTimeString.split(":");
    time.setHours(Integer.parseInt(reminderTimeSplit[0]));
    time.setMinutes(Integer.parseInt(reminderTimeSplit[1]));
    time.setSeconds(0);
    RemindersItem item = new RemindersItem();
    UUID randomUUID = UUID.randomUUID();
    item.setId(randomUUID.toString());
    item.setStartDate(startDate);
    item.setTime(time);
    remindersAdapter.addItem(item);
    newRemindersEditText.setText("");
}

8. CachedDateFormatTest#test1()

Project: log4j
Source File: CachedDateFormatTest.java
View license
/**
   * Test multiple calls in close intervals.
   */
public void test1() {
    //   subsequent calls within one minute
    //     are optimized to reuse previous formatted value
    //     make a couple of nearly spaced calls
    DateFormat gmtFormat = new CachedDateFormat(createAbsoluteTimeDateFormat(GMT), 1000);
    long ticks = 12601L * 86400000L;
    Date jul1 = new Date(ticks);
    assertEquals("00:00:00,000", gmtFormat.format(jul1));
    Date plus8ms = new Date(ticks + 8);
    assertEquals("00:00:00,008", gmtFormat.format(plus8ms));
    Date plus17ms = new Date(ticks + 17);
    assertEquals("00:00:00,017", gmtFormat.format(plus17ms));
    Date plus237ms = new Date(ticks + 237);
    assertEquals("00:00:00,237", gmtFormat.format(plus237ms));
    Date plus1415ms = new Date(ticks + 1415);
    assertEquals("00:00:01,415", gmtFormat.format(plus1415ms));
}

9. CachedDateFormatTest#test3()

Project: log4j
Source File: CachedDateFormatTest.java
View license
/**
   * Test multiple calls in close intervals prior to 1 Jan 1970.
   */
public void test3() {
    //   subsequent calls within one minute
    //     are optimized to reuse previous formatted value
    //     make a couple of nearly spaced calls
    DateFormat gmtFormat = new CachedDateFormat(createAbsoluteTimeDateFormat(GMT), 1000);
    //
    //  if the first call was exactly on an integral
    //     second, it would not test the round toward zero compensation
    long ticks = -7L * 86400000L;
    Date jul1 = new Date(ticks + 8);
    assertEquals("00:00:00,008", gmtFormat.format(jul1));
    Date plus8ms = new Date(ticks + 16);
    assertEquals("00:00:00,016", gmtFormat.format(plus8ms));
    Date plus17ms = new Date(ticks + 23);
    assertEquals("00:00:00,023", gmtFormat.format(plus17ms));
    Date plus237ms = new Date(ticks + 245);
    assertEquals("00:00:00,245", gmtFormat.format(plus237ms));
    Date plus1415ms = new Date(ticks + 1423);
    assertEquals("00:00:01,423", gmtFormat.format(plus1415ms));
}

10. CachedDateFormatTest#test4()

Project: log4j
Source File: CachedDateFormatTest.java
View license
public void test4() {
    //  subsequent calls within one minute are optimized to reuse previous 
    //  formatted value. make a couple of nearly spaced calls
    // (Note: 'Z' is JDK 1.4, using 'z' instead.)
    SimpleDateFormat baseFormat = new SimpleDateFormat("EEE, MMM dd, HH:mm:ss.SSS z", Locale.ENGLISH);
    DateFormat cachedFormat = new CachedDateFormat(baseFormat, 1000);
    //
    //   use a date in 2000 to attempt to confuse the millisecond locator
    long ticks = 11141L * 86400000L;
    Date jul1 = new Date(ticks);
    assertEquals(baseFormat.format(jul1), cachedFormat.format(jul1));
    Date plus8ms = new Date(ticks + 8);
    String base = baseFormat.format(plus8ms);
    String cached = cachedFormat.format(plus8ms);
    assertEquals(baseFormat.format(plus8ms), cachedFormat.format(plus8ms));
    Date plus17ms = new Date(ticks + 17);
    assertEquals(baseFormat.format(plus17ms), cachedFormat.format(plus17ms));
    Date plus237ms = new Date(ticks + 237);
    assertEquals(baseFormat.format(plus237ms), cachedFormat.format(plus237ms));
    Date plus1415ms = new Date(ticks + 1415);
    assertEquals(baseFormat.format(plus1415ms), cachedFormat.format(plus1415ms));
}

11. DateUtilsTest#testCompareDateEndWithMinute()

Project: ngrinder
Source File: DateUtilsTest.java
View license
@SuppressWarnings("deprecation")
@Test
public void testCompareDateEndWithMinute() {
    Date date1 = new Date();
    date1.setSeconds(0);
    Date date2 = new Date(date1.getTime());
    date2.setSeconds(10);
    assertTrue(DateUtils.compareDateEndWithMinute(date1, date2));
    assertTrue(DateUtils.compareDateEndWithMinute(date1, date1));
    date2 = new Date(date1.getTime());
    if (date1.getMinutes() > 1) {
        date2.setMinutes(date1.getMinutes() - 1);
    } else {
        date2.setMinutes(date1.getMinutes() + 1);
    }
    assertTrue(!DateUtils.compareDateEndWithMinute(date1, date2));
}

12. TestCoordJobGetActionsForDatesJPAExecutor#testCoordActionGet()

View license
public void testCoordActionGet() throws Exception {
    int actionNum = 1;
    CoordinatorJobBean job = addRecordToCoordJobTable(CoordinatorJob.Status.RUNNING, false, false);
    addRecordToCoordActionTable(job.getId(), actionNum, CoordinatorAction.Status.FAILED, "coord-action-get.xml", 0);
    Path appPath = new Path(getFsTestCaseDir(), "coord");
    String actionXml = getCoordActionXml(appPath, "coord-action-get.xml");
    String actionNomialTime = getActionNominalTime(actionXml);
    Date nominalTime = DateUtils.parseDateUTC(actionNomialTime);
    Date d1 = new Date(nominalTime.getTime() - 1000);
    Date d2 = new Date(nominalTime.getTime() + 1000);
    _testGetActionForDates(job.getId(), d1, d2, 1);
    d1 = new Date(nominalTime.getTime() + 1000);
    d2 = new Date(nominalTime.getTime() + 2000);
    _testGetActionForDates(job.getId(), d1, d2, 0);
    cleanUpDBTables();
    job = addRecordToCoordJobTable(CoordinatorJob.Status.RUNNING, false, false);
    addRecordToCoordActionTable(job.getId(), actionNum, CoordinatorAction.Status.WAITING, "coord-action-get.xml", 0);
    _testGetActionForDates(job.getId(), d1, d2, 0);
}

13. HttpHeaderDateFormatTest#testParse()

Project: netty
Source File: HttpHeaderDateFormatTest.java
View license
@Test
public void testParse() throws ParseException {
    HttpHeaderDateFormat format = HttpHeaderDateFormat.get();
    final Date parsedDateWithSingleDigitDay = format.parse("Sun, 6 Nov 1994 08:49:37 GMT");
    assertNotNull(parsedDateWithSingleDigitDay);
    assertEquals(DATE, parsedDateWithSingleDigitDay);
    final Date parsedDateWithDoubleDigitDay = format.parse("Sun, 06 Nov 1994 08:49:37 GMT");
    assertNotNull(parsedDateWithDoubleDigitDay);
    assertEquals(DATE, parsedDateWithDoubleDigitDay);
    final Date parsedDateWithDashSeparatorSingleDigitDay = format.parse("Sunday, 06-Nov-94 08:49:37 GMT");
    assertNotNull(parsedDateWithDashSeparatorSingleDigitDay);
    assertEquals(DATE, parsedDateWithDashSeparatorSingleDigitDay);
    final Date parsedDateWithSingleDoubleDigitDay = format.parse("Sunday, 6-Nov-94 08:49:37 GMT");
    assertNotNull(parsedDateWithSingleDoubleDigitDay);
    assertEquals(DATE, parsedDateWithSingleDoubleDigitDay);
    final Date parsedDateWithoutGMT = format.parse("Sun Nov 6 08:49:37 1994");
    assertNotNull(parsedDateWithoutGMT);
    assertEquals(DATE, parsedDateWithoutGMT);
}

14. TimeRangeCalendarTest#testIsTimeIncluded()

Project: openhab
Source File: TimeRangeCalendarTest.java
View license
@Test
public void testIsTimeIncluded() throws ParseException {
    Date startTime = DATE_FORMATTER.parse("04.04.2012 16:00:00:000");
    Date endTime = DATE_FORMATTER.parse("04.04.2012 19:15:00:000");
    Date included = DATE_FORMATTER.parse("04.04.2012 19:00:00:000");
    Date excluded_before = DATE_FORMATTER.parse("04.04.2012 15:59:59:999");
    Date excluded_after = DATE_FORMATTER.parse("04.04.2012 19:15:00:001");
    LongRange timeRange = new LongRange(startTime.getTime(), endTime.getTime());
    calendar.addTimeRange(timeRange);
    Assert.assertEquals(true, calendar.isTimeIncluded(included.getTime()));
    Assert.assertEquals(false, calendar.isTimeIncluded(excluded_before.getTime()));
    Assert.assertEquals(false, calendar.isTimeIncluded(excluded_after.getTime()));
}

15. ReengagementService#getNextReminderTime()

Project: astrid
Source File: ReengagementService.java
View license
private static long getNextReminderTime() {
    int reengagementReminders = Preferences.getInt(PREF_REENGAGEMENT_COUNT, 1);
    int days;
    if (DateUtilities.now() - Preferences.getLong(AstridPreferences.P_FIRST_LAUNCH, 0) > DateUtilities.ONE_DAY * 30) {
        // Installed longer than 30 days
        // Sequence: every 6, 8, 10 days
        days = Math.min(10, 4 + 2 * reengagementReminders);
    } else {
        // Sequence: every 2, 3, 4, 5 days
        days = Math.min(5, 1 + reengagementReminders);
    }
    Date date = new Date(DateUtilities.now() + DateUtilities.ONE_DAY * days / 1000L * 1000L);
    date.setHours(18);
    date.setMinutes(0);
    date.setSeconds(0);
    return date.getTime();
}

16. PrintCharts#printPatientChart()

Project: buendia
Source File: PrintCharts.java
View license
private void printPatientChart(List<Obs> observations, String chartName, List<Concept> questionConcepts, PrintWriter w) {
    w.write("<h3>" + chartName + "</h3>");
    // NOTE: this assumes that the list of observations will have a length of at least 1.
    assert observations.size() > 0;
    final Date earliest = observations.get(observations.size() - 1).getObsDatetime();
    final Date latest = observations.get(0).getObsDatetime();
    // We already know the earliest date and the latest date, so we can start splitting up into
    // weeks.
    final Date earliestDay = getStartOfDay(earliest);
    HashMap<Concept, Map<Date, List<Obs>>> obsByConcept = constructObsMap(observations, earliestDay);
    // Each loop iteration is a week.
    Date weekStart = earliestDay;
    Calendar weekCal = Calendar.getInstance();
    weekCal.setTime(earliestDay);
    while (weekStart.before(latest)) {
        writeWeek(w, weekStart, questionConcepts, obsByConcept);
        weekCal.add(Calendar.DATE, 7);
        weekStart = weekCal.getTime();
    }
}

17. PermaSql#replaceEodValues()

Project: astrid
Source File: PermaSql.java
View license
private static String replaceEodValues(String value) {
    Date date = new Date();
    date.setHours(23);
    date.setMinutes(59);
    date.setSeconds(59);
    // chop milliseconds off
    long time = date.getTime() / 1000l * 1000l;
    value = value.replace(VALUE_EOD_YESTERDAY, Long.toString(time - DateUtilities.ONE_DAY));
    value = value.replace(VALUE_EOD, Long.toString(time));
    value = value.replace(VALUE_EOD_TOMORROW, Long.toString(time + DateUtilities.ONE_DAY));
    value = value.replace(VALUE_EOD_DAY_AFTER, Long.toString(time + 2 * DateUtilities.ONE_DAY));
    value = value.replace(VALUE_EOD_NEXT_WEEK, Long.toString(time + 7 * DateUtilities.ONE_DAY));
    value = value.replace(VALUE_EOD_NEXT_MONTH, Long.toString(time + 30 * DateUtilities.ONE_DAY));
    return value;
}

18. PermaSql#replaceNoonValues()

Project: astrid
Source File: PermaSql.java
View license
private static String replaceNoonValues(String value) {
    Date date = new Date();
    date.setHours(12);
    date.setMinutes(0);
    date.setSeconds(0);
    // chop milliseconds off
    long time = date.getTime() / 1000l * 1000l;
    value = value.replace(VALUE_NOON_YESTERDAY, Long.toString(time - DateUtilities.ONE_DAY));
    value = value.replace(VALUE_NOON, Long.toString(time));
    value = value.replace(VALUE_NOON_TOMORROW, Long.toString(time + DateUtilities.ONE_DAY));
    value = value.replace(VALUE_NOON_DAY_AFTER, Long.toString(time + 2 * DateUtilities.ONE_DAY));
    value = value.replace(VALUE_NOON_NEXT_WEEK, Long.toString(time + 7 * DateUtilities.ONE_DAY));
    value = value.replace(VALUE_NOON_NEXT_MONTH, Long.toString(time + 30 * DateUtilities.ONE_DAY));
    return value;
}

19. AdvancedRepeatTests#testCompletionDateSpecificTime()

Project: astrid
Source File: AdvancedRepeatTests.java
View license
public void testCompletionDateSpecificTime() throws ParseException {
    buildRRule(1, Frequency.DAILY);
    // test specific day & time
    long dayWithTime = Task.createDueDate(Task.URGENCY_SPECIFIC_DAY_TIME, new Date(110, 7, 1, 10, 4, 0).getTime());
    task.setValue(Task.DUE_DATE, dayWithTime);
    Date todayWithTime = new Date();
    todayWithTime.setHours(10);
    todayWithTime.setMinutes(4);
    todayWithTime.setSeconds(1);
    long nextDayWithTimeLong = todayWithTime.getTime();
    nextDayWithTimeLong += DateUtilities.ONE_DAY;
    nextDayWithTimeLong = nextDayWithTimeLong / 1000L * 1000;
    nextDueDate = RepeatTaskCompleteListener.computeNextDueDate(task, rrule.toIcal(), true);
    assertDateTimeEquals(nextDayWithTimeLong, nextDueDate);
}

20. GtasksNewSyncTest#createLocalTaskForDateTests()

Project: astrid
Source File: GtasksNewSyncTest.java
View license
/*
     * Helper method for due date tests
     */
private Task createLocalTaskForDateTests(String addToTitle) {
    Task localTask = createNewLocalTask("Due date will change" + addToTitle);
    Date date = new Date(115, 2, 14);
    date.setHours(12);
    date.setMinutes(0);
    date.setSeconds(0);
    long dueDate = date.getTime();
    localTask.setValue(Task.DUE_DATE, dueDate);
    taskService.save(localTask);
    return localTask;
}

21. RepeatTestsGtasksSync#assertTaskExistsRemotely()

Project: astrid
Source File: RepeatTestsGtasksSync.java
View license
@Override
protected com.google.api.services.tasks.model.Task assertTaskExistsRemotely(Task t, long expectedRemoteTime) {
    Metadata metadata = gtasksMetadataService.getTaskMetadata(t.getId());
    assertNotNull(metadata);
    String listId = metadata.getValue(GtasksMetadata.LIST_ID);
    String taskId = metadata.getValue(GtasksMetadata.ID);
    com.google.api.services.tasks.model.Task remote = null;
    try {
        remote = gtasksService.getGtask(listId, taskId);
    } catch (IOException e) {
        e.printStackTrace();
        fail("Exception in gtasks service");
    }
    assertNotNull(remote);
    assertEquals(t.getValue(Task.TITLE), remote.getTitle());
    Date expected = new Date(expectedRemoteTime);
    expected.setHours(0);
    expected.setMinutes(0);
    expected.setSeconds(0);
    long gtasksTime = GtasksApiUtilities.gtasksDueTimeToUnixTime(remote.getDue(), 0);
    assertTimesMatch(expected.getTime(), gtasksTime);
    return remote;
}

22. DatabaseUtils#addOrders()

Project: Bar-Piinqcite
Source File: DatabaseUtils.java
View license
private List<Order> addOrders() {
    List<Order> orders = new ArrayList<Order>();
    Date date = new Date();
    Order order = new Order(new Timestamp(date.getTime()), USERS[1], MARTIN_S_TABLE);
    orderDAO.addOrder(order);
    orders.add(order);
    date = new Date();
    order = new Order(new Timestamp(date.getTime()), USERS[3], 1l);
    orderDAO.addOrder(order);
    orders.add(order);
    date = new Date();
    order = new Order(new Timestamp(date.getTime()), USERS[1], 2l);
    orderDAO.addOrder(order);
    orders.add(order);
    date = new Date();
    order = new Order(new Timestamp(date.getTime()), USERS[3], 3l);
    orderDAO.addOrder(order);
    orders.add(order);
    return orders;
}

23. TokenTest#setUp()

Project: directory-kerby
Source File: TokenTest.java
View license
@Before
public void setUp() {
    authToken = KrbRuntime.getTokenProvider().createTokenFactory().createToken();
    authToken.setIssuer(ISSUER);
    authToken.setSubject(SUBJECT);
    authToken.addAttribute("group", GROUP);
    authToken.addAttribute("role", ROLE);
    auds.add(AUDIENCE);
    authToken.setAudiences(auds);
    // Set expiration in 60 minutes
    final Date now = new Date();
    Date exp = new Date(now.getTime() + 1000 * 60 * 60);
    authToken.setExpirationTime(exp);
    Date nbf = now;
    authToken.setNotBeforeTime(nbf);
    Date iat = now;
    authToken.setIssueTime(iat);
}

24. VisibleMonthsTest#should_calculate2()

View license
@Test
public void should_calculate2() {
    Date date1 = new Date(1000);
    Date date2 = new Date(2000);
    Date date3 = new Date(3000);
    Date date4 = new Date(4000);
    VisibleMonths tested = new VisibleMonths(new VisibleMonth(Arrays.asList(new Day(date1), new Day(date2))), new VisibleMonth(Arrays.asList(new Day(date3))), new VisibleMonth(Arrays.asList(new Day(date4))), Collections.<String>emptyList());
    assertThat(tested.getCount()).isEqualTo(4);
    assertThat(tested.getAt(0).getDate()).isEqualTo(date1);
    assertThat(tested.getAt(1).getDate()).isEqualTo(date2);
    assertThat(tested.getAt(2).getDate()).isEqualTo(date3);
    assertThat(tested.getAt(3).getDate()).isEqualTo(date4);
}

25. IssuesFinderSortTest#should_sort_by_creation_date()

Project: sonarqube
Source File: IssuesFinderSortTest.java
View license
@Test
public void should_sort_by_creation_date() {
    Date date = new Date();
    Date date1 = DateUtils.addDays(date, -3);
    Date date2 = DateUtils.addDays(date, -2);
    Date date3 = DateUtils.addDays(date, -1);
    IssueDto issue1 = new IssueDto().setId(1L).setIssueCreationDate(date1);
    IssueDto issue2 = new IssueDto().setId(2L).setIssueCreationDate(date3);
    IssueDto issue3 = new IssueDto().setId(3L).setIssueCreationDate(date2);
    List<IssueDto> dtoList = newArrayList(issue1, issue2, issue3);
    IssueQuery query = IssueQuery.builder(userSessionRule).sort(IssueQuery.SORT_BY_CREATION_DATE).asc(false).build();
    IssuesFinderSort issuesFinderSort = new IssuesFinderSort(dtoList, query);
    List<IssueDto> result = newArrayList(issuesFinderSort.sort());
    assertThat(result).hasSize(3);
    assertThat(result.get(0).getIssueCreationDate()).isEqualTo(date3);
    assertThat(result.get(1).getIssueCreationDate()).isEqualTo(date2);
    assertThat(result.get(2).getIssueCreationDate()).isEqualTo(date1);
}

26. IssuesFinderSortTest#should_sort_by_update_date()

Project: sonarqube
Source File: IssuesFinderSortTest.java
View license
@Test
public void should_sort_by_update_date() {
    Date date = new Date();
    Date date1 = DateUtils.addDays(date, -3);
    Date date2 = DateUtils.addDays(date, -2);
    Date date3 = DateUtils.addDays(date, -1);
    IssueDto issue1 = new IssueDto().setId(1L).setIssueUpdateDate(date1);
    IssueDto issue2 = new IssueDto().setId(2L).setIssueUpdateDate(date3);
    IssueDto issue3 = new IssueDto().setId(3L).setIssueUpdateDate(date2);
    List<IssueDto> dtoList = newArrayList(issue1, issue2, issue3);
    IssueQuery query = IssueQuery.builder(userSessionRule).sort(IssueQuery.SORT_BY_UPDATE_DATE).asc(false).build();
    IssuesFinderSort issuesFinderSort = new IssuesFinderSort(dtoList, query);
    List<IssueDto> result = newArrayList(issuesFinderSort.sort());
    assertThat(result).hasSize(3);
    assertThat(result.get(0).getIssueUpdateDate()).isEqualTo(date3);
    assertThat(result.get(1).getIssueUpdateDate()).isEqualTo(date2);
    assertThat(result.get(2).getIssueUpdateDate()).isEqualTo(date1);
}

27. IssuesFinderSortTest#should_sort_by_close_date()

Project: sonarqube
Source File: IssuesFinderSortTest.java
View license
@Test
public void should_sort_by_close_date() {
    Date date = new Date();
    Date date1 = DateUtils.addDays(date, -3);
    Date date2 = DateUtils.addDays(date, -2);
    Date date3 = DateUtils.addDays(date, -1);
    IssueDto issue1 = new IssueDto().setId(1L).setIssueCloseDate(date1);
    IssueDto issue2 = new IssueDto().setId(2L).setIssueCloseDate(date3);
    IssueDto issue3 = new IssueDto().setId(3L).setIssueCloseDate(date2);
    List<IssueDto> dtoList = newArrayList(issue1, issue2, issue3);
    IssueQuery query = IssueQuery.builder(userSessionRule).sort(IssueQuery.SORT_BY_CLOSE_DATE).asc(false).build();
    IssuesFinderSort issuesFinderSort = new IssuesFinderSort(dtoList, query);
    List<IssueDto> result = newArrayList(issuesFinderSort.sort());
    assertThat(result).hasSize(3);
    assertThat(result.get(0).getIssueCloseDate()).isEqualTo(date3);
    assertThat(result.get(1).getIssueCloseDate()).isEqualTo(date2);
    assertThat(result.get(2).getIssueCloseDate()).isEqualTo(date1);
}

28. FolderMarkGroupFilterTest#setUp()

View license
/**
   * @throws Exception
   */
@Before
public void setUp() throws Exception {
    ((PersistenceServiceImpl) Owl.getPersistenceService()).recreateSchemaForTests();
    fFactory = Owl.getModelFactory();
    fGrouping = new BookMarkGrouping();
    fFiltering = new BookMarkFilter();
    fToday = new Date(DateUtils.getToday().getTimeInMillis() + 1000);
    fYesterday = new Date(fToday.getTime() - DAY);
    Calendar today = DateUtils.getToday();
    fTodayIsFirstDayOfWeek = today.get(Calendar.DAY_OF_WEEK) == today.getFirstDayOfWeek();
    fYesterdayIsFirstDayOfWeek = today.get(Calendar.DAY_OF_WEEK) == today.getFirstDayOfWeek() + 1;
    today.set(Calendar.DAY_OF_WEEK, today.getFirstDayOfWeek());
    fEarlierThisWeek = new Date(today.getTimeInMillis() + 1000);
    fLastWeek = new Date(fEarlierThisWeek.getTime() - WEEK);
}

29. NewsGroupFilterTest#setUp()

Project: RSSOwl
Source File: NewsGroupFilterTest.java
View license
/**
   * @throws Exception
   */
@Before
public void setUp() throws Exception {
    fFactory = Owl.getModelFactory();
    fGrouping = new NewsGrouping();
    fFiltering = new NewsFilter();
    fToday = new Date(DateUtils.getToday().getTimeInMillis());
    fYesterday = new Date(fToday.getTime() - DAY);
    Calendar today = DateUtils.getToday();
    fTodayIsFirstDayOfWeek = today.get(Calendar.DAY_OF_WEEK) == today.getFirstDayOfWeek();
    fYesterdayIsFirstDayOfWeek = today.get(Calendar.DAY_OF_WEEK) == today.getFirstDayOfWeek() + 1;
    today.set(Calendar.DAY_OF_WEEK, today.getFirstDayOfWeek());
    fEarlierThisWeek = new Date(today.getTimeInMillis() + 1000);
    fLastWeek = new Date(fEarlierThisWeek.getTime() - WEEK);
    ((PersistenceServiceImpl) Owl.getPersistenceService()).recreateSchemaForTests();
}

30. DateRangeTest#testUnion()

Project: sis
Source File: DateRangeTest.java
View license
/**
     * Tests {@link Range#union(Range)}.
     */
@Test
public void testUnion() {
    final Date min = date("1998-04-02 13:00:00");
    final Date in1 = date("1998-05-12 11:00:00");
    final Date in2 = date("1998-06-08 14:00:00");
    final Date max = date("1998-07-01 19:00:00");
    final Range<Date> r1 = new Range<Date>(Date.class, min, true, in2, true);
    final Range<Date> r2 = new Range<Date>(Date.class, in1, true, max, true);
    final Range<Date> rt = r1.union(r2);
    assertEquals(min, rt.getMinValue());
    assertEquals(max, rt.getMaxValue());
    assertEquals(rt, r2.union(r1));
    /*
         * Test a range fully included in the other range.
         */
    final Range<Date> outer = new Range<Date>(Date.class, min, true, max, true);
    final Range<Date> inner = new Range<Date>(Date.class, in1, true, in2, true);
    assertSame(outer, outer.union(inner));
    assertSame(outer, inner.union(outer));
}

31. DateRangeTest#testIntersect()

Project: sis
Source File: DateRangeTest.java
View license
/**
     * Tests {@link Range#intersect(Range)}.
     */
@Test
public void testIntersect() {
    final Date min = date("1998-04-02 13:00:00");
    final Date in1 = date("1998-05-12 11:00:00");
    final Date in2 = date("1998-06-08 14:00:00");
    final Date max = date("1998-07-01 19:00:00");
    final Range<Date> r1 = new Range<Date>(Date.class, min, true, in2, true);
    final Range<Date> r2 = new Range<Date>(Date.class, in1, true, max, true);
    final Range<Date> rt = r1.intersect(r2);
    assertEquals(in1, rt.getMinValue());
    assertEquals(in2, rt.getMaxValue());
    assertEquals(rt, r2.intersect(r1));
    /*
         * Test a range fully included in the other range.
         */
    final Range<Date> outer = new Range<Date>(Date.class, min, true, max, true);
    final Range<Date> inner = new Range<Date>(Date.class, in1, true, in2, true);
    assertSame(inner, outer.intersect(inner));
    assertSame(inner, inner.intersect(outer));
}

32. DateRangeTest#testSubtract()

Project: sis
Source File: DateRangeTest.java
View license
/**
     * Tests {@link Range#subtract(Range)}.
     */
@Test
public void testSubtract() {
    final Date min = date("1998-04-02 13:00:00");
    final Date in1 = date("1998-05-12 11:00:00");
    final Date in2 = date("1998-06-08 14:00:00");
    final Date max = date("1998-07-01 19:00:00");
    final Range<Date> outer = new Range<Date>(Date.class, min, true, max, true);
    final Range<Date> inner = new Range<Date>(Date.class, in1, true, in2, true);
    final Range<Date>[] rt = outer.subtract(inner);
    assertEquals(2, rt.length);
    assertEquals(min, rt[0].getMinValue());
    assertEquals(in1, rt[0].getMaxValue());
    assertEquals(in2, rt[1].getMinValue());
    assertEquals(max, rt[1].getMaxValue());
}

33. AppleForkedDateEntry#decode()

View license
public void decode(final byte[] dateEntry) {
    //$NON-NLS-1$
    Check.notNull(dateEntry, "dateEntry");
    //$NON-NLS-1$
    Check.isTrue(dateEntry.length == DATE_ENTRY_SIZE, "dateEntry.length == DATE_ENTRY_SIZE");
    final long javaCreationTime = getJavaTime(ByteArrayUtils.getUnsignedInt32(dateEntry, 0));
    final long javaModificationTime = getJavaTime(ByteArrayUtils.getUnsignedInt32(dateEntry, 4));
    final long javaBackupTime = getJavaTime(ByteArrayUtils.getUnsignedInt32(dateEntry, 8));
    final long javaAccessTime = getJavaTime(ByteArrayUtils.getUnsignedInt32(dateEntry, 12));
    creationDate = new Date(javaCreationTime);
    modificationDate = new Date(javaModificationTime);
    backupDate = new Date(javaBackupTime);
    accessDate = new Date(javaAccessTime);
}

34. TimeRangeCalendarTest#testGetNextIncludedTime()

Project: openhab
Source File: TimeRangeCalendarTest.java
View license
@Test
public void testGetNextIncludedTime() throws ParseException {
    Date startTime = DATE_FORMATTER.parse("04.04.2012 16:00:00:000");
    Date endTime = DATE_FORMATTER.parse("04.04.2012 19:15:00:000");
    Date included = DATE_FORMATTER.parse("04.04.2012 17:23:21:000");
    Date expected = DATE_FORMATTER.parse("04.04.2012 19:15:00:001");
    LongRange timeRange = new LongRange(startTime.getTime(), endTime.getTime());
    calendar.addTimeRange(timeRange);
    Assert.assertEquals(expected.getTime(), calendar.getNextIncludedTime(included.getTime()));
}

35. TimeParsing#main()

Project: openjdk
Source File: TimeParsing.java
View license
public static void main(String args[]) throws Exception {
    Date d0 = new Date(TIME);
    System.out.println(d0.toGMTString());
    checkUTC(d0, UTC_ZULU, "Zulu");
    checkUTC(d0, UTC_PLUS1, "+0100");
    checkUTC(d0, UTC_MINUS1, "-0100");
    checkGeneralized(d0, GEN_ZULU, "Zulu");
    checkGeneralized(d0, GEN_PLUS1, "+0100");
    checkGeneralized(d0, GEN_MINUS1, "-0100");
    Date d1 = new Date(TIME_FRACT1);
    checkGeneralized(d1, GEN_FRACT1_ZULU, "fractional seconds (Zulu)");
    checkGeneralized(d1, GEN_FRACT1_PLUS1, "fractional seconds (+0100)");
    Date d2 = new Date(TIME_FRACT2);
    checkGeneralized(d2, GEN_FRACT2_ZULU, "fractional seconds (Zulu)");
    checkGeneralized(d2, GEN_FRACT2_PLUS1, "fractional seconds (+0100)");
    Date d3 = new Date(TIME_FRACT3);
    checkGeneralized(d3, GEN_FRACT3_ZULU, "fractional seconds (Zulu)");
    checkGeneralized(d3, GEN_FRACT3_PLUS1, "fractional seconds (+0100)");
    checkGeneralized(d3, GEN_FRACT3_COMMA_PLUS1, "fractional seconds (+0100)");
}

36. TimeParsing#main()

Project: jdk7u-jdk
Source File: TimeParsing.java
View license
public static void main(String args[]) throws Exception {
    Date d0 = new Date(TIME);
    System.out.println(d0.toGMTString());
    checkUTC(d0, UTC_ZULU, "Zulu");
    checkUTC(d0, UTC_PLUS1, "+0100");
    checkUTC(d0, UTC_MINUS1, "-0100");
    checkGeneralized(d0, GEN_ZULU, "Zulu");
    checkGeneralized(d0, GEN_PLUS1, "+0100");
    checkGeneralized(d0, GEN_MINUS1, "-0100");
    Date d1 = new Date(TIME_FRACT1);
    checkGeneralized(d1, GEN_FRACT1_ZULU, "fractional seconds (Zulu)");
    checkGeneralized(d1, GEN_FRACT1_PLUS1, "fractional seconds (+0100)");
    Date d2 = new Date(TIME_FRACT2);
    checkGeneralized(d2, GEN_FRACT2_ZULU, "fractional seconds (Zulu)");
    checkGeneralized(d2, GEN_FRACT2_PLUS1, "fractional seconds (+0100)");
    Date d3 = new Date(TIME_FRACT3);
    checkGeneralized(d3, GEN_FRACT3_ZULU, "fractional seconds (Zulu)");
    checkGeneralized(d3, GEN_FRACT3_PLUS1, "fractional seconds (+0100)");
    checkGeneralized(d3, GEN_FRACT3_COMMA_PLUS1, "fractional seconds (+0100)");
}

37. DateAxisTest#testSetMaximumDate()

Project: jfreechart-fse
Source File: DateAxisTest.java
View license
/**
     * Test that the setMaximumDate() method works.
     */
@Test
public void testSetMaximumDate() {
    DateAxis axis = new DateAxis("Test Axis");
    Date date = new Date();
    axis.setMaximumDate(date);
    assertEquals(date, axis.getMaximumDate());
    // check that setting the max date to something on or before the
    // current min date works...
    Date d1 = new Date();
    Date d2 = new Date(d1.getTime() + 1);
    Date d0 = new Date(d1.getTime() - 1);
    axis.setMaximumDate(d2);
    axis.setMinimumDate(d1);
    axis.setMaximumDate(d1);
    assertEquals(d0, axis.getMinimumDate());
}

38. LogsArchiveImplTest#test_scanPeriod()

View license
@Test
public void test_scanPeriod() {
    long scanPeriod = ARCH_SCAN_PERIOD;
    assertEquals(1000 * 60 * 60 * 24, scanPeriod);
    Date now = new Date();
    Date noNeedScanDate = new Date(now.getTime() - scanPeriod + 5000);
    Date needScanDate = new Date(now.getTime() - scanPeriod - 5000);
    LogsArchiveImpl arc = new LogsArchiveImpl();
    assertNotNull(arc.tryCreateArcsIfNeed(TEST_DIR, "test", null));
    assertEquals(now, arc.tryCreateArcsIfNeed(TEST_DIR, "test", now));
    assertEquals(noNeedScanDate, arc.tryCreateArcsIfNeed(TEST_DIR, "test", noNeedScanDate));
    Date newDate = arc.tryCreateArcsIfNeed(TEST_DIR, "test", needScanDate);
    assertTrue(newDate + " " + now, newDate.compareTo(now) > -1);
}

39. DateTimeUtilsTest#testDateWithZone()

Project: mycollab
Source File: DateTimeUtilsTest.java
View license
@Test
public void testDateWithZone() {
    TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
    DateTimeZone.setDefault(DateTimeZone.UTC);
    Date value = new GregorianCalendar(2012, 11, 20).getTime();
    Date newDate = DateTimeUtils.convertDateTimeToUTC(value);
    Assert.assertEquals(value.getTime(), newDate.getTime());
    Date newDate2 = DateTimeUtils.trimHMSOfDate(newDate);
    Assert.assertEquals(value.getTime(), newDate2.getTime());
    Date newDate3 = DateTimeUtils.trimHMSOfDate(DateTimeUtils.convertDateTimeToUTC(value));
    Assert.assertEquals(value.getTime(), newDate3.getTime());
}

40. CubeFactTableTest#factProperties()

Project: lens
Source File: CubeFactTableTest.java
View license
@DataProvider(name = "properties")
public Object[][] factProperties() throws LensException {
    String minus1DaysRelative = "now -1 days";
    String minus2DaysRelative = "now -2 days";
    String plus1DaysRelative = "now +1 days";
    String plus2DaysRelative = "now +2 days";
    String minus1DaysAbsolute = DateUtil.relativeToAbsolute(minus1DaysRelative, now);
    String minus2DaysAbsolute = DateUtil.relativeToAbsolute(minus2DaysRelative, now);
    String plus1DaysAbsolute = DateUtil.relativeToAbsolute(plus1DaysRelative, now);
    String plus2DaysAbsolute = DateUtil.relativeToAbsolute(plus2DaysRelative, now);
    Date minus1DaysDate = DateUtil.resolveRelativeDate(minus1DaysRelative, now);
    Date minus2DaysDate = DateUtil.resolveRelativeDate(minus2DaysRelative, now);
    Date plus1DaysDate = DateUtil.resolveRelativeDate(plus1DaysRelative, now);
    Date plus2DaysDate = DateUtil.resolveRelativeDate(plus2DaysRelative, now);
    return new Object[][] { { null, null, null, null, new Date(Long.MIN_VALUE), new Date(Long.MAX_VALUE) }, { null, minus2DaysRelative, null, plus2DaysRelative, minus2DaysDate, plus2DaysDate }, { minus2DaysAbsolute, null, plus2DaysAbsolute, null, minus2DaysDate, plus2DaysDate }, { minus1DaysAbsolute, minus2DaysRelative, plus1DaysAbsolute, plus2DaysRelative, minus1DaysDate, plus1DaysDate }, { minus2DaysAbsolute, minus1DaysRelative, plus2DaysAbsolute, plus1DaysRelative, minus1DaysDate, plus1DaysDate } };
}

41. ParseConfigTest#testGetDateKeyExist()

View license
//endregion
//region testGetDate
@Test
public void testGetDateKeyExist() throws Exception {
    final Date date = new Date();
    date.setTime(10);
    Date dateAgain = new Date();
    dateAgain.setTime(20);
    final Map<String, Object> params = new HashMap<>();
    params.put("key", date);
    ParseConfig config = new ParseConfig(params);
    assertEquals(date.getTime(), config.getDate("key").getTime());
    assertEquals(date.getTime(), config.getDate("key", dateAgain).getTime());
}

42. ParseConfigTest#testGetDateKeyNotExist()

View license
@Test
public void testGetDateKeyNotExist() throws Exception {
    final Date date = new Date();
    date.setTime(10);
    Date dateAgain = new Date();
    dateAgain.setTime(10);
    final Map<String, Object> params = new HashMap<>();
    params.put("key", date);
    ParseConfig config = new ParseConfig(params);
    assertNull(config.getDate("wrongKey"));
    assertSame(dateAgain, config.getDate("wrongKey", dateAgain));
}

43. CalendarEventGenerator#getFullDayDateFields()

Project: zxing
Source File: CalendarEventGenerator.java
View license
private String getFullDayDateFields() throws GeneratorException {
    Date date1 = datePicker1.getValue();
    Date date2 = datePicker2.getValue();
    if (date1 == null || date2 == null) {
        throw new GeneratorException("Start and end dates must be set.");
    }
    if (date1.after(date2)) {
        throw new GeneratorException("End date cannot be before start date.");
    }
    // Specify end date as +1 day since it's exclusive
    Date date2PlusDay = new Date(date2.getTime() + 24 * 60 * 60 * 1000);
    DateTimeFormat isoFormatter = DateTimeFormat.getFormat("yyyyMMdd");
    StringBuilder output = new StringBuilder();
    output.append("DTSTART;VALUE=DATE:");
    output.append(isoFormatter.format(date1));
    output.append("\r\n");
    output.append("DTEND;VALUE=DATE:");
    output.append(isoFormatter.format(date2PlusDay));
    output.append("\r\n");
    return output.toString();
}

44. LateRerunHandler#getEventDelay()

Project: falcon
Source File: LateRerunHandler.java
View license
//SUSPEND CHECKSTYLE CHECK ParameterNumberCheck
private long getEventDelay(Entity entity, String nominalTime) throws FalconException {
    Date instanceDate = EntityUtil.parseDateUTC(nominalTime);
    LateProcess lateProcess = EntityUtil.getLateProcess(entity);
    if (lateProcess == null) {
        LOG.warn("Late run not applicable for entity: {} ({})", entity.getEntityType(), entity.getName());
        return -1;
    }
    PolicyType latePolicy = lateProcess.getPolicy();
    Date cutOffTime = getCutOffTime(entity, nominalTime);
    Date now = new Date();
    Long wait;
    if (now.after(cutOffTime)) {
        LOG.warn("Feed Cut Off time: {} has expired, Late Rerun can not be scheduled", SchemaHelper.formatDateUTC(cutOffTime));
        return -1;
    } else {
        AbstractRerunPolicy rerunPolicy = RerunPolicyFactory.getRetryPolicy(latePolicy);
        wait = rerunPolicy.getDelay(lateProcess.getDelay(), instanceDate, cutOffTime);
    }
    return wait;
}

45. CrossEntityValidations#validateFeedRetentionPeriod()

Project: falcon
Source File: CrossEntityValidations.java
View license
public static void validateFeedRetentionPeriod(String startInstance, Feed feed, String clusterName) throws FalconException {
    String feedRetention = FeedHelper.getCluster(feed, clusterName).getRetention().getLimit().toString();
    ExpressionHelper evaluator = ExpressionHelper.get();
    Date now = new Date();
    ExpressionHelper.setReferenceDate(now);
    Date instStart = evaluator.evaluate(startInstance, Date.class);
    long feedDuration = evaluator.evaluate(feedRetention, Long.class);
    Date feedStart = new Date(now.getTime() - feedDuration);
    if (instStart.before(feedStart)) {
        throw new ValidationException("StartInstance :" + startInstance + " of process is out of range for Feed: " + feed.getName() + "  in cluster: " + clusterName + "'s retention limit :" + feedRetention);
    }
}

46. JTreeTable#formatDate()

View license
public static String formatDate(Date date) {
    final Date midnight = new Date();
    midnight.setHours(0);
    midnight.setMinutes(0);
    midnight.setSeconds(0);
    SimpleDateFormat format;
    if (date.before(midnight)) {
        // FULL DATE
        format = ISO_8601_FORMAT;
    } else {
        format = TIME_FORMAT;
    }
    final String formatted = format.format(date);
    return formatted;
}

47. DateTest#test_compareToLjava_util_Date()

Project: j2objc
Source File: DateTest.java
View license
/**
	 * @tests java.util.Date#compareTo(java.util.Date)
	 */
public void test_compareToLjava_util_Date() {
    // Test for method int java.util.Date.compareTo(java.util.Date)
    final int someNumber = 10000;
    Date d1 = new Date(someNumber);
    Date d2 = new Date(someNumber);
    Date d3 = new Date(someNumber + 1);
    Date d4 = new Date(someNumber - 1);
    assertEquals("Comparing a date to itself did not answer zero", 0, d1.compareTo(d1));
    assertEquals("Comparing equal dates did not answer zero", 0, d1.compareTo(d2));
    assertEquals("date1.compareTo(date2), where date1 > date2, did not result in 1", 1, d1.compareTo(d4));
    assertEquals("date1.compareTo(date2), where date1 < date2, did not result in -1", -1, d1.compareTo(d3));
}

48. DateUtil#processPostedDates()

Project: shopizer
Source File: DateUtil.java
View license
public void processPostedDates(HttpServletRequest request) {
    Date dt = new Date();
    DateFormat myDateFormat = new SimpleDateFormat(Constants.DEFAULT_DATE_FORMAT);
    Date sDate = null;
    Date eDate = null;
    try {
        if (request.getParameter("startdate") != null) {
            sDate = myDateFormat.parse(request.getParameter("startdate"));
        }
        if (request.getParameter("enddate") != null) {
            eDate = myDateFormat.parse(request.getParameter("enddate"));
        }
        this.startDate = sDate;
        this.endDate = eDate;
    } catch (Exception e) {
        LOGGER.error("", e);
        this.startDate = new Date(dt.getTime());
        this.endDate = new Date(dt.getTime());
    }
}

49. DateUtilsTest#testGet()

Project: metamodel
Source File: DateUtilsTest.java
View license
public void testGet() throws Exception {
    SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date christmasDay = DateUtils.get(2010, Month.DECEMBER, 24);
    assertEquals("2010-12-24 00:00:00", f.format(christmasDay));
    assertEquals(Weekday.FRIDAY, DateUtils.getWeekday(christmasDay));
    Date date2 = DateUtils.get(christmasDay, 1);
    assertEquals("2010-12-25 00:00:00", f.format(date2));
    Date date3 = DateUtils.get(christmasDay, 10);
    assertEquals("2011-01-03 00:00:00", f.format(date3));
}

50. LimitingResourceQueueModel#doGlobalView()

View license
private void doGlobalView() {
    master = PredefinedScenarios.MASTER.getScenario();
    List<LimitingResourceQueueElement> unassigned = findUnassignedLimitingResourceQueueElements();
    List<LimitingResourceQueue> queues = loadLimitingResourceQueues();
    queuesState = new QueuesState(queues, unassigned);
    final Date startingDate = getEarliestDate();
    Date endDate = (new LocalDate(startingDate)).plusYears(2).toDateTimeAtCurrentTime().toDate();
    viewInterval = new Interval(startingDate, endDate);
    Date currentDate = new Date();
    viewInterval = new Interval(startingDate.after(currentDate) ? currentDate : startingDate, endDate);
}

51. TestDateUtil#testRelativeToAbsolute()

Project: lens
Source File: TestDateUtil.java
View license
@Test
public void testRelativeToAbsolute() throws LensException {
    Date now = new Date();
    Date nowDay = DateUtils.truncate(now, DAY_OF_MONTH);
    Date nowDayMinus2Days = DateUtils.add(nowDay, DAY_OF_MONTH, -2);
    assertEquals(relativeToAbsolute("now", now), DateUtil.ABSDATE_PARSER.get().format(now));
    assertEquals(relativeToAbsolute("now.day", now), DateUtil.ABSDATE_PARSER.get().format(nowDay));
    assertEquals(relativeToAbsolute("now.day - 2 days", now), DateUtil.ABSDATE_PARSER.get().format(nowDayMinus2Days));
    assertEquals(relativeToAbsolute("now.day - 2 day", now), DateUtil.ABSDATE_PARSER.get().format(nowDayMinus2Days));
    assertEquals(relativeToAbsolute("now.day - 2day", now), DateUtil.ABSDATE_PARSER.get().format(nowDayMinus2Days));
    assertEquals(relativeToAbsolute("now.day -2 day", now), DateUtil.ABSDATE_PARSER.get().format(nowDayMinus2Days));
    assertEquals(relativeToAbsolute("now.day -2 days", now), DateUtil.ABSDATE_PARSER.get().format(nowDayMinus2Days));
}

52. FilterBaseTest#buildINCompareFilter()

Project: kylin
Source File: FilterBaseTest.java
View license
protected CompareTupleFilter buildINCompareFilter(TblColRef dateColumn) throws ParseException {
    CompareTupleFilter compareFilter = new CompareTupleFilter(FilterOperatorEnum.IN);
    ColumnTupleFilter columnFilter = new ColumnTupleFilter(dateColumn);
    compareFilter.addChild(columnFilter);
    List<String> inValues = Lists.newArrayList();
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    Date startDate = simpleDateFormat.parse("1970-01-01");
    Date endDate = simpleDateFormat.parse("2100-01-01");
    Calendar start = Calendar.getInstance();
    start.setTime(startDate);
    Calendar end = Calendar.getInstance();
    end.setTime(endDate);
    for (Date date = start.getTime(); start.before(end); start.add(Calendar.DATE, 1), date = start.getTime()) {
        inValues.add(simpleDateFormat.format(date));
    }
    ConstantTupleFilter constantFilter = new ConstantTupleFilter(inValues);
    compareFilter.addChild(constantFilter);
    return compareFilter;
}

53. EncounterDAOTest#getSavedEncounterDatetime_shouldGetSavedEncounterDatetimeFromDatabase()

Project: openmrs-core
Source File: EncounterDAOTest.java
View license
/**
	 * @see EncounterDAO#getSavedEncounterDatetime(Encounter)
	 */
@Test
@Verifies(value = "should get saved encounter datetime from database", method = "getSavedEncounterDatetime(Encounter)")
public void getSavedEncounterDatetime_shouldGetSavedEncounterDatetimeFromDatabase() throws Exception {
    Encounter encounter = Context.getEncounterService().getEncounter(1);
    Date newDate = new Date();
    // sanity check: make sure the date on the encounter isn't "right now" 
    assertNotSame(encounter.getEncounterDatetime(), newDate);
    // save the date from the db for later checks
    Date origDate = encounter.getEncounterDatetime();
    // change the date on the java pojo (NOT in the database)
    encounter.setEncounterDatetime(newDate);
    // the value from the database should match the original date from the 
    // encounter right after /it/ was fetched from the database
    Date encounterDateFromDatabase = dao.getSavedEncounterDatetime(encounter);
    assertEquals(origDate, encounterDateFromDatabase);
}

54. bug8008657#createDateSpinner()

Project: openjdk
Source File: bug8008657.java
View license
static void createDateSpinner() {
    Calendar calendar = Calendar.getInstance();
    Date initDate = calendar.getTime();
    calendar.add(Calendar.YEAR, -1);
    Date earliestDate = calendar.getTime();
    calendar.add(Calendar.YEAR, 1);
    Date latestDate = calendar.getTime();
    SpinnerModel dateModel = new SpinnerDateModel(initDate, earliestDate, latestDate, Calendar.YEAR);
    spinner = new JSpinner();
    spinner.setModel(dateModel);
}

55. TestCoordMaterializeTransitionXCommand#testActionMaterWithPauseTime3()

View license
/**
     * Job start time is after pause time, should pause the job.
     *
     * @throws Exception
     */
public void testActionMaterWithPauseTime3() throws Exception {
    Date startTime = DateUtils.parseDateUTC("2009-03-06T10:00Z");
    Date endTime = DateUtils.parseDateUTC("2009-03-06T10:14Z");
    Date pauseTime = DateUtils.parseDateUTC("2009-03-06T09:58Z");
    final CoordinatorJobBean job = addRecordToCoordJobTable(CoordinatorJob.Status.RUNNING, startTime, endTime, pauseTime);
    new CoordMaterializeTransitionXCommand(job.getId(), 3600).call();
    waitFor(1000 * 60, new Predicate() {

        public boolean evaluate() throws Exception {
            return (getStatus(job.getId()) == CoordinatorJob.Status.PAUSED ? true : false);
        }
    });
    checkCoordActions(job.getId(), 0, CoordinatorJob.Status.PAUSED);
}

56. DateUtilsTest#testConvertToUserDate()

Project: ngrinder
Source File: DateUtilsTest.java
View license
@Test
public void testConvertToUserDate() {
    String userLocaleId = "Asia/Seoul";
    TimeZone tz = TimeZone.getTimeZone(userLocaleId);
    Date serverDate = new Date();
    Date userDate = DateUtils.convertToUserDate(userLocaleId, serverDate);
    assertThat((int) (userDate.getTime() - serverDate.getTime()), is(tz.getRawOffset() - TimeZone.getDefault().getRawOffset()));
    // convert the server date back to test.
    Date newServerDate = DateUtils.convertToServerDate(userLocaleId, userDate);
    assertThat(serverDate.getTime(), is(newServerDate.getTime()));
}

57. DailyTaskAdaptor#getWhen()

Project: jPOS
Source File: DailyTaskAdaptor.java
View license
public Date getWhen() {
    // NOPMD
    String s = cfg.get("start") + ":00:00";
    int hh = Integer.parseInt(s.substring(0, 2));
    int mm = Integer.parseInt(s.substring(3, 5));
    int ss = Integer.parseInt(s.substring(6, 8));
    Date now = new Date();
    Calendar cal = new GregorianCalendar();
    cal.setTime(now);
    cal.set(Calendar.HOUR_OF_DAY, hh);
    cal.set(Calendar.MINUTE, mm);
    cal.set(Calendar.SECOND, ss);
    Date when = cal.getTime();
    if (when.before(now))
        when = new Date(when.getTime() + 24 * 60 * 60 * 1000);
    return when;
}

58. SimpleTimePeriodTest#testImmutable()

View license
/**
     * Some simple checks for immutability.
     */
@Test
public void testImmutable() {
    SimpleTimePeriod p1 = new SimpleTimePeriod(new Date(10L), new Date(20L));
    SimpleTimePeriod p2 = new SimpleTimePeriod(new Date(10L), new Date(20L));
    assertEquals(p1, p2);
    p1.getStart().setTime(11L);
    assertEquals(p1, p2);
    Date d1 = new Date(10L);
    Date d2 = new Date(20L);
    p1 = new SimpleTimePeriod(d1, d2);
    d1.setTime(11L);
    assertEquals(new Date(10L), p1.getStart());
}

59. DateAxisTest#testSetMinimumDate()

Project: jfreechart-fse
Source File: DateAxisTest.java
View license
/**
     * Test that the setMinimumDate() method works.
     */
@Test
public void testSetMinimumDate() {
    DateAxis axis = new DateAxis("Test Axis");
    Date d1 = new Date();
    Date d2 = new Date(d1.getTime() + 1);
    axis.setMaximumDate(d2);
    axis.setMinimumDate(d1);
    assertEquals(d1, axis.getMinimumDate());
    // check that setting the min date to something on or after the
    // current min date works...
    Date d3 = new Date(d2.getTime() + 1);
    axis.setMinimumDate(d2);
    assertEquals(d3, axis.getMaximumDate());
}

60. ForumRepository#getForumStats()

Project: jforum3
Source File: ForumRepository.java
View license
public ForumStats getForumStats() {
    ForumStats s = new ForumStats();
    s.setPosts(this.getTotalMessages());
    s.setTotalUsers(((Number) session.createQuery("select count(*) from User").uniqueResult()).intValue());
    s.setTotalTopics(((Number) session.createQuery("select count(*) from Topic").uniqueResult()).intValue());
    Date today = new Date();
    Date firstPostDate = (Date) session.createQuery("select min(p.date) from Post p").uniqueResult();
    s.setPostsPerDay(firstPostDate != null ? (double) s.getPosts() / this.daysUntilToday(today, firstPostDate) : 0);
    s.setTopicsPerDay(firstPostDate != null ? (double) s.getTopics() / this.daysUntilToday(today, firstPostDate) : 0);
    Date firstRegisteredUserDate = (Date) session.createQuery("select min(u.registrationDate) from User u").uniqueResult();
    s.setUsersPerDay(firstRegisteredUserDate != null ? (double) s.getUsers() / this.daysUntilToday(today, firstRegisteredUserDate) : 0);
    return s;
}

61. SSLSocketFactoryFactory#generateCA()

View license
private void generateCA(X500Principal caName) throws GeneralSecurityException, IOException, OperatorCreationException {
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    keyGen.initialize(1024);
    KeyPair caPair = keyGen.generateKeyPair();
    caKey = caPair.getPrivate();
    PublicKey caPubKey = caPair.getPublic();
    Date begin = new Date();
    begin.setTime(begin.getTime() - DEFAULT_AGE);
    Date ends = new Date(begin.getTime() + DEFAULT_VALIDITY);
    X509Certificate cert = SunCertificateUtils.sign(caName, caPubKey, caName, caPubKey, caKey, begin, ends, BigInteger.ONE, null);
    caCerts = new X509Certificate[] { cert };
    keystore.setKeyEntry(CA, caKey, password, caCerts);
    saveKeystore();
}

62. EntryGuards#needsUnreachableTest()

Project: Orchid
Source File: EntryGuards.java
View license
private boolean needsUnreachableTest(GuardEntry entry) {
    final Date downSince = entry.getDownSince();
    if (downSince == null || !entry.testCurrentlyUsable()) {
        return false;
    }
    final Date now = new Date();
    final Date lastConnect = entry.getLastConnectAttempt();
    final long timeDown = now.getTime() - downSince.getTime();
    final long timeSinceLastRetest = (lastConnect == null) ? timeDown : (now.getTime() - lastConnect.getTime());
    return timeSinceLastRetest > getRetestInterval(timeDown);
}

63. DateFieldRanges#updateValuesForDateField()

Project: vaadin
Source File: DateFieldRanges.java
View license
private void updateValuesForDateField(DateField df) {
    Date fromVal = fromRange.getValue();
    Date toVal = toRange.getValue();
    Date value = valueDF.getValue();
    Resolution r = (Resolution) resoSelect.getValue();
    boolean immediate = immediateCB.getValue();
    df.setValue(value);
    df.setResolution(r);
    df.setRangeStart(fromVal);
    df.setRangeEnd(toVal);
    df.setImmediate(immediate);
}

64. BasicDateClickHandler#dateClick()

Project: vaadin
Source File: BasicDateClickHandler.java
View license
/*
     * (non-Javadoc)
     * 
     * @see
     * com.vaadin.addon.calendar.ui.CalendarComponentEvents.DateClickHandler
     * #dateClick
     * (com.vaadin.addon.calendar.ui.CalendarComponentEvents.DateClickEvent)
     */
@Override
public void dateClick(DateClickEvent event) {
    Date clickedDate = event.getDate();
    Calendar javaCalendar = event.getComponent().getInternalCalendar();
    javaCalendar.setTime(clickedDate);
    // as times are expanded, this is all that is needed to show one day
    Date start = javaCalendar.getTime();
    Date end = javaCalendar.getTime();
    setDates(event, start, end);
}

65. SignupUIBaseBean#setSignupBeginDeadlineData()

Project: sakai
Source File: SignupUIBaseBean.java
View license
/**
	 * setup the event/meeting's signup begin and deadline time and validate it
	 * too
	 */
protected void setSignupBeginDeadlineData(SignupMeeting meeting, int signupBegin, String signupBeginType, int signupDeadline, String signupDeadlineType) throws Exception {
    Date sBegin = Utilities.subTractTimeToDate(meeting.getStartTime(), signupBegin, signupBeginType);
    Date sDeadline = Utilities.subTractTimeToDate(meeting.getEndTime(), signupDeadline, signupDeadlineType);
    if (!START_NOW.equals(signupBeginType) && sBegin.before(new Date())) {
        // a warning for user
        Utilities.addErrorMessage(Utilities.rb.getString("warning.your.event.singup.begin.time.passed.today.time"));
    }
    meeting.setSignupBegins(sBegin);
    if (sBegin.after(sDeadline))
        throw new SignupUserActionException(Utilities.rb.getString("signup.deadline.is.before.signup.begin"));
    meeting.setSignupDeadline(sDeadline);
}

66. EditMeeting#setSignupBeginDeadlineData()

Project: sakai
Source File: EditMeeting.java
View license
/**
	 * setup the event/meeting's signup begin and deadline time and validate it
	 * too
	 */
private void setSignupBeginDeadlineData(SignupMeeting meeting, int signupBegin, String signupBeginType, int signupDeadline, String signupDeadlineType) throws Exception {
    Date sBegin = Utilities.subTractTimeToDate(meeting.getStartTime(), signupBegin, signupBeginType);
    Date sDeadline = Utilities.subTractTimeToDate(meeting.getEndTime(), signupDeadline, signupDeadlineType);
    // ????
    boolean origSignupStarted = originalMeetingCopy.getSignupBegins().before(new Date());
    /* TODO have to pass it in?? */
    if (!START_NOW.equals(signupBeginType) && sBegin.before(new Date()) && !origSignupStarted) {
        // a warning for user
        Utilities.addErrorMessage(Utilities.rb.getString("warning.your.event.singup.begin.time.passed.today.time"));
    }
    if (!isSignupBeginModifiedByUser() && this.isStartNowTypeForRecurEvents) {
    /*do nothing and keep the original value since the Sign-up process is already started
			 * No need to re-assign a new start_now value*/
    } else {
        meeting.setSignupBegins(sBegin);
    }
    if (sBegin.after(sDeadline))
        throw new SignupUserActionException(Utilities.rb.getString("signup.deadline.is.before.signup.begin"));
    meeting.setSignupDeadline(sDeadline);
}

67. ProspectiveSearchServlet#isSubscriptionActive()

View license
/**
   * Checks if subscriptions for the device are active.
   *
   * @param deviceId A unique device identifier
   * @return True, if subscriptions are active; False, the otherwise
   */
private boolean isSubscriptionActive(String deviceId) {
    Date lastDeleteAll = backendConfigManager.getLastSubscriptionDeleteAllTime();
    // still active.
    if (lastDeleteAll == null) {
        return true;
    }
    Entity deviceEntity = deviceSubscription.get(deviceId);
    if (deviceEntity == null) {
        return false;
    }
    Date latestSubscriptionTime = (Date) deviceEntity.getProperty(DeviceSubscription.PROPERTY_TIMESTAMP);
    return latestSubscriptionTime.after(lastDeleteAll);
}

68. RecurrenceExpressionTest#getFinalTimeCheck()

View license
@Test
public void getFinalTimeCheck() throws ParseException {
    Calendar cal = Calendar.getInstance();
    // set to Jan 1st 2016, 00:00
    cal.set(2016, 0, 1, 0, 0, 0);
    Date startDate = cal.getTime();
    // This rule describes an event that takes place on every weekday (BYDAY) for the next 15 weekdays (COUNT).
    RecurrenceExpression expr = new RecurrenceExpression("FREQ=DAILY;BYDAY=MO,TU,WE,TH,FR;COUNT=15", startDate);
    Date nextDate = expr.getFinalFireTime();
    cal.set(2016, 0, 21, 0, 0, 0);
    Date checkDate = cal.getTime();
    assertEquals(checkDate, nextDate);
}

69. RecurrenceExpressionTest#IntervalCheck()

View license
@Test
public void IntervalCheck() throws ParseException {
    Calendar cal = Calendar.getInstance();
    // set to Jan 1st 2016, 00:00
    cal.set(2016, 0, 1, 0, 0, 0);
    Date startDate = cal.getTime();
    // US election day. Every fourth year (INTERVAL) on the first Tuesday (BYDAY) after a Monday (BYMONTHDAY ensures
    // that) in November (BYMONTH).
    RecurrenceExpression expr = new RecurrenceExpression("FREQ=YEARLY;INTERVAL=4;BYMONTH=11;BYDAY=TU;BYMONTHDAY=2,3,4,5,6,7,8", startDate);
    Date nextDate = expr.getTimeAfter(startDate);
    nextDate = expr.getTimeAfter(nextDate);
    cal.set(2020, 10, 3, 0, 0, 0);
    Date checkDate = cal.getTime();
    assertEquals(checkDate, nextDate);
}

70. RecurrenceExpressionTest#getTimeAfterCheck()

View license
@Test
public void getTimeAfterCheck() throws ParseException {
    Calendar cal = Calendar.getInstance();
    // set to Jan 1st 2016, 00:00
    cal.set(2016, 0, 1, 0, 0, 0);
    Date startDate = cal.getTime();
    // This rule describes an event that takes place on every weekday (BYDAY) for the next 15 weekdays (COUNT).
    RecurrenceExpression expr = new RecurrenceExpression("FREQ=DAILY;BYDAY=MO,TU,WE,TH,FR;COUNT=15", startDate);
    Date nextDate = expr.getTimeAfter(startDate);
    cal.set(2016, 0, 4, 0, 0, 0);
    Date checkDate = cal.getTime();
    assertEquals(checkDate, nextDate);
}

71. DateExpressionTest#getFinalTimeCheck()

Project: smarthome
Source File: DateExpressionTest.java
View license
@Test
public void getFinalTimeCheck() throws ParseException {
    Calendar cal = Calendar.getInstance();
    // set to Jan 1st 2016, 00:00
    cal.set(2016, 0, 1, 0, 0, 0);
    cal.setTimeZone(TimeZone.getTimeZone("GMT+00"));
    Date startDate = cal.getTime();
    DateExpression expr = new DateExpression("2016-01-31T00:00:00+00:00");
    expr.setStartDate(startDate);
    expr.setTimeZone(TimeZone.getTimeZone("GMT+00"));
    Date nextDate = expr.getFinalFireTime();
    cal.set(2016, 0, 31, 0, 0, 0);
    cal.set(Calendar.MILLISECOND, 0);
    cal.setTimeZone(TimeZone.getTimeZone("GMT+00"));
    Date checkDate = cal.getTime();
    assertEquals(checkDate, nextDate);
}

72. DateExpressionTest#getTimeAfterCheck()

Project: smarthome
Source File: DateExpressionTest.java
View license
@Test
public void getTimeAfterCheck() throws ParseException {
    Calendar cal = Calendar.getInstance();
    // set to Jan 1st 2016, 00:00
    cal.set(2016, 0, 1, 0, 0, 0);
    cal.setTimeZone(TimeZone.getTimeZone("GMT+00"));
    Date startDate = cal.getTime();
    DateExpression expr = new DateExpression("2016-01-31T00:00:00+00:00");
    expr.setStartDate(startDate);
    expr.setTimeZone(TimeZone.getTimeZone("GMT+00"));
    Date nextDate = expr.getTimeAfter(startDate);
    cal.set(2016, 0, 31, 0, 0, 0);
    cal.set(Calendar.MILLISECOND, 0);
    cal.setTimeZone(TimeZone.getTimeZone("GMT+00"));
    Date checkDate = cal.getTime();
    assertEquals(checkDate, nextDate);
}

73. CronExpressionTest#getFinalTimeCheck()

Project: smarthome
Source File: CronExpressionTest.java
View license
@Test
public void getFinalTimeCheck() throws ParseException {
    Calendar cal = Calendar.getInstance();
    // set to Jan 1st 2016, 00:00
    cal.set(2016, 0, 1, 0, 0, 0);
    Date startDate = cal.getTime();
    // Fire at 10:15am on every last friday of every month during the years 2016 to 2020
    CronExpression expr = new CronExpression("0 15 10 ? * 6L 2016-2020", startDate);
    Date nextDate = expr.getFinalFireTime();
    cal.set(2020, 11, 25, 10, 15, 0);
    Date checkDate = cal.getTime();
    assertEquals(checkDate, nextDate);
}

74. CronExpressionTest#getTimeAfterCheck()

Project: smarthome
Source File: CronExpressionTest.java
View license
@Test
public void getTimeAfterCheck() throws ParseException {
    Calendar cal = Calendar.getInstance();
    // set to Jan 1st 2016, 00:00
    cal.set(2016, 0, 1, 0, 0, 0);
    Date startDate = cal.getTime();
    // Fire at 10:15am on the third Friday of every month
    CronExpression expr = new CronExpression("0 15 10 ? * 6#3", startDate);
    Date nextDate = expr.getTimeAfter(startDate);
    cal.set(2016, 0, 15, 10, 15, 0);
    Date checkDate = cal.getTime();
    assertEquals(checkDate, nextDate);
}

75. UnmodifiableParameterValueTest#testGetValue()

View license
/**
     * Verifies that {@link UnmodifiableParameterValue#getValue()} can clone the value.
     */
@Test
@DependsOnMethod("testCreate")
public void testGetValue() {
    final ParameterValue<Date> modifiable = DefaultParameterDescriptorTest.createSimpleOptional("Time reference", Date.class).createValue();
    modifiable.setValue(date("1994-01-01 00:00:00"));
    /*
         * Create and validate an unmodifiable parameter,
         * then verify that the values are not the same.
         */
    final DefaultParameterValue<Date> unmodifiable = assertEquivalent(modifiable);
    final Date t1 = modifiable.getValue();
    final Date t2 = unmodifiable.getValue();
    assertNotSame("Date should be cloned.", t1, t2);
    assertEquals(t1, t2);
    /*
         * Verify that cloning the parameter also clone its value.
         */
    final DefaultParameterValue<Date> clone = unmodifiable.clone();
    assertEquals(DefaultParameterValue.class, clone.getClass());
    final Date t3 = clone.getValue();
    assertNotSame(t1, t3);
    assertNotSame(t2, t3);
    assertEquals(t1, t3);
}

76. IssueIndex#addDatesFilter()

Project: sonarqube
Source File: IssueIndex.java
View license
private void addDatesFilter(Map<String, QueryBuilder> filters, IssueQuery query) {
    Date createdAfter = query.createdAfter();
    Date createdBefore = query.createdBefore();
    validateCreationDateBounds(createdBefore, createdAfter);
    if (createdAfter != null) {
        filters.put("__createdAfter", QueryBuilders.rangeQuery(IssueIndexDefinition.FIELD_ISSUE_FUNC_CREATED_AT).gte(createdAfter));
    }
    if (createdBefore != null) {
        filters.put("__createdBefore", QueryBuilders.rangeQuery(IssueIndexDefinition.FIELD_ISSUE_FUNC_CREATED_AT).lt(createdBefore));
    }
    Date createdAt = query.createdAt();
    if (createdAt != null) {
        filters.put("__createdAt", termQuery(IssueIndexDefinition.FIELD_ISSUE_FUNC_CREATED_AT, createdAt));
    }
}

77. JwtHttpHandler#validateToken()

Project: sonarqube
Source File: JwtHttpHandler.java
View license
private Optional<UserDto> validateToken(String tokenEncoded, HttpServletRequest request, HttpServletResponse response) {
    Optional<Claims> claims = jwtSerializer.decode(tokenEncoded);
    if (!claims.isPresent()) {
        return Optional.empty();
    }
    Date now = new Date(system2.now());
    Claims token = claims.get();
    if (now.after(DateUtils.addSeconds(token.getIssuedAt(), SESSION_DISCONNECT_IN_SECONDS))) {
        return Optional.empty();
    }
    jwtCsrfVerifier.verifyState(request, (String) token.get(CSRF_JWT_PARAM));
    if (now.after(DateUtils.addSeconds(getLastRefreshDate(token), SESSION_REFRESH_IN_SECONDS))) {
        refreshToken(token, response);
    }
    Optional<UserDto> user = selectUserFromDb(token.getSubject());
    if (!user.isPresent()) {
        return Optional.empty();
    }
    return Optional.of(user.get());
}

78. TrustUtil#createLifetimeElement()

Project: rampart
Source File: TrustUtil.java
View license
public static OMElement createLifetimeElement(int version, OMElement parent, long ttl) throws TrustException {
    Date creationTime = new Date();
    Date expirationTime = new Date();
    expirationTime.setTime(creationTime.getTime() + ttl);
    DateFormat zulu = new XmlSchemaDateFormat();
    return createLifetimeElement(version, parent, zulu.format(creationTime), zulu.format(expirationTime));
}

79. TimeSeriesBuilderCallbackTest#setUp()

View license
@Override
protected void setUp() throws Exception {
    super.setUp();
    Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT+00:00"));
    calendar.set(2013, Calendar.JANUARY, 1);
    Date jan1 = calendar.getTime();
    calendar.set(2013, Calendar.JANUARY, 2);
    Date jan2 = calendar.getTime();
    calendar.set(2013, Calendar.JANUARY, 3);
    Date jan3 = calendar.getTime();
    _dates = new Date[] { jan1, jan2, jan3 };
    _values = new double[] { 2.0, 4.0, 8.0 };
}

80. PreferencesTest#testLastUpdatedDateIsImmutable()

Project: qpid-java
Source File: PreferencesTest.java
View license
public void testLastUpdatedDateIsImmutable() throws Exception {
    final Preference p1 = Subject.doAs(_testSubject, new PrivilegedAction<Preference>() {

        @Override
        public Preference run() {
            return _testObject.getUserPreferences().createPreference(null, "X-testType", "propName1", null, null, Collections.<String, Object>emptyMap());
        }
    });
    Date lastUpdatedDate = p1.getLastUpdatedDate();
    lastUpdatedDate.setTime(0);
    Date lastUpdatedDate2 = p1.getLastUpdatedDate();
    assertTrue("Creation date is not immutable.", lastUpdatedDate2.getTime() != 0);
}

81. PreferencesTest#testLastUpdatedDate()

Project: qpid-java
Source File: PreferencesTest.java
View license
public void testLastUpdatedDate() throws Exception {
    Date before = new Date();
    Thread.sleep(1);
    final Preference p1 = Subject.doAs(_testSubject, new PrivilegedAction<Preference>() {

        @Override
        public Preference run() {
            return _testObject.getUserPreferences().createPreference(null, "X-testType", "propName1", null, null, Collections.<String, Object>emptyMap());
        }
    });
    Thread.sleep(1);
    Date after = new Date();
    Date lastUpdatedDate = p1.getLastUpdatedDate();
    assertTrue(String.format("Creation date is too early. Expected : after %s  Found : %s", before, lastUpdatedDate), before.before(lastUpdatedDate));
    assertTrue(String.format("Creation date is too late. Expected : after %s  Found : %s", after, lastUpdatedDate), after.after(lastUpdatedDate));
}

82. MockDateTest#testMockDateWithEasyMock()

Project: powermock
Source File: MockDateTest.java
View license
@Test
public void testMockDateWithEasyMock() throws Exception {
    Date someDate = new Date();
    MocksControl c = (MocksControl) org.easymock.EasyMock.createControl();
    Date date = c.createMock(Date.class);
    EasyMock.expect(date.after(someDate)).andReturn(false);
    PowerMock.replay(date);
    date.after(someDate);
    PowerMock.verify(date);
}

83. MockDateTest#testMockDate()

Project: powermock
Source File: MockDateTest.java
View license
@Test
public void testMockDate() throws Exception {
    Date someDate = new Date();
    Date date = PowerMock.createMock(Date.class);
    EasyMock.expect(date.after(someDate)).andReturn(false);
    PowerMock.replay(date);
    date.after(someDate);
    PowerMock.verify(date);
}

84. PlutusAndroid#fetchRequired()

Project: PlutusAndroid
Source File: PlutusAndroid.java
View license
public boolean fetchRequired() {
    // if pauseTime was earlier than 1 hour ago
    Date pauseDate = ioService.getFetchDate();
    if (pauseDate == null) {
        Log.i("Data status", "empty preferences -- no data");
        ioService.saveNewInstallation(false);
        return true;
    }
    Date now = new Date(System.currentTimeMillis());
    Calendar cal = Calendar.getInstance();
    cal.setTime(pauseDate);
    cal.add(Calendar.MINUTE, Config.APP_DEFAULT_SNOOZE_TIME);
    Log.i("Data status", "now: " + now);
    Log.i("Data status", "last: " + pauseDate);
    Log.i("Data status", "snooze: " + cal.getTime());
    Log.i("Data status", "fetch required: " + now.after(cal.getTime()));
    return now.after(cal.getTime());
}

85. DateTest#test()

Project: pluotsorbet
Source File: DateTest.java
View license
public void test(TestHarness th) {
    Date d = new Date();
    // This test is not reliable:
    // compare(d.getTime(), System.currentTimeMillis());
    Date d2 = new Date(4873984739798L);
    th.check(d2.getTime(), 4873984739798L);
    th.check(!d.equals(d2));
    th.check(d2.hashCode(), -803140168);
    th.check(d2.toString().indexOf("2124") != -1);
    d.setTime(4873984739798L);
    th.check(d.equals(d2));
}

86. HttpClientRequestImplTest#testSetDateHeaderMulti()

View license
@Test(timeout = 60000)
public void testSetDateHeaderMulti() throws Exception {
    String headerName = "date";
    Date date1 = new Date();
    HttpClientRequestImpl<Object, ByteBuf> addReq = requestRule.request.addDateHeader(headerName, date1);
    requestRule.assertCopy(addReq);
    requestRule.assertHeaderAdded(addReq, headerName, date1);
    Date date2 = new Date(100);
    Date date3 = new Date(500);
    HttpClientRequestImpl<Object, ByteBuf> setReq = requestRule.request.setDateHeader(headerName, Arrays.asList(date2, date3));
    requestRule.assertCopy(setReq);
    requestRule.assertHeaderAdded(setReq, headerName, date2, date3);
}

87. TimeUtilsUnitTests#canGetDuration()

Project: genie
Source File: TimeUtilsUnitTests.java
View license
/**
     * Can get the duration for various cases.
     */
@Test
public void canGetDuration() {
    final Date epoch = new Date(0);
    final long durationMillis = 50823L;
    final Duration duration = Duration.ofMillis(durationMillis);
    final Date started = new Date();
    final Date finished = new Date(started.getTime() + durationMillis);
    Assert.assertThat(TimeUtils.getDuration(null, finished), Matchers.is(Duration.ZERO));
    Assert.assertThat(TimeUtils.getDuration(epoch, finished), Matchers.is(Duration.ZERO));
    Assert.assertNotNull(TimeUtils.getDuration(started, null));
    Assert.assertNotNull(TimeUtils.getDuration(started, epoch));
    Assert.assertThat(TimeUtils.getDuration(started, finished), Matchers.is(duration));
}

88. DurationBusinessCalendarTest#testSimpleDuration()

View license
public void testSimpleDuration() throws Exception {
    DurationBusinessCalendar businessCalendar = new DurationBusinessCalendar();
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy MM dd - HH:mm");
    Date now = simpleDateFormat.parse("2010 06 11 - 17:23");
    ClockUtil.setCurrentTime(now);
    Date duedate = businessCalendar.resolveDuedate("P2DT5H70M");
    Date expectedDuedate = simpleDateFormat.parse("2010 06 13 - 23:33");
    assertEquals(expectedDuedate, duedate);
}

89. CycleBusinessCalendarTest#testSimpleDuration()

View license
public void testSimpleDuration() throws Exception {
    CycleBusinessCalendar businessCalendar = new CycleBusinessCalendar();
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy MM dd - HH:mm");
    Date now = simpleDateFormat.parse("2010 06 11 - 17:23");
    ClockUtil.setCurrentTime(now);
    Date duedate = businessCalendar.resolveDuedate("R/P2DT5H70M");
    Date expectedDuedate = simpleDateFormat.parse("2010 06 13 - 23:33");
    assertEquals(expectedDuedate, duedate);
}

90. CycleBusinessCalendarTest#testSimpleCron()

View license
public void testSimpleCron() throws Exception {
    CycleBusinessCalendar businessCalendar = new CycleBusinessCalendar();
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy MM dd - HH:mm");
    Date now = simpleDateFormat.parse("2011 03 11 - 17:23");
    ClockUtil.setCurrentTime(now);
    Date duedate = businessCalendar.resolveDuedate("0 0 0 1 * ?");
    Date expectedDuedate = simpleDateFormat.parse("2011 04 1 - 00:00");
    assertEquals(expectedDuedate, duedate);
}

91. HistoricDecisionInstanceTest#testQueryByEvaluatedAfter()

View license
@Deployment(resources = { DECISION_PROCESS, DECISION_SINGLE_OUTPUT_DMN })
public void testQueryByEvaluatedAfter() {
    Date beforeEvaluated = new Date(1441612000);
    Date evaluated = new Date(1441613000);
    Date afterEvaluated = new Date(1441614000);
    ClockUtil.setCurrentTime(evaluated);
    startProcessInstanceAndEvaluateDecision();
    HistoricDecisionInstanceQuery query = historyService.createHistoricDecisionInstanceQuery();
    assertThat(query.evaluatedAfter(beforeEvaluated).count(), is(1L));
    assertThat(query.evaluatedAfter(evaluated).count(), is(1L));
    assertThat(query.evaluatedAfter(afterEvaluated).count(), is(0L));
    ClockUtil.reset();
}

92. HistoricDecisionInstanceTest#testQueryByEvaluatedBefore()

View license
@Deployment(resources = { DECISION_PROCESS, DECISION_SINGLE_OUTPUT_DMN })
public void testQueryByEvaluatedBefore() {
    Date beforeEvaluated = new Date(1441612000);
    Date evaluated = new Date(1441613000);
    Date afterEvaluated = new Date(1441614000);
    ClockUtil.setCurrentTime(evaluated);
    startProcessInstanceAndEvaluateDecision();
    HistoricDecisionInstanceQuery query = historyService.createHistoricDecisionInstanceQuery();
    assertThat(query.evaluatedBefore(afterEvaluated).count(), is(1L));
    assertThat(query.evaluatedBefore(evaluated).count(), is(1L));
    assertThat(query.evaluatedBefore(beforeEvaluated).count(), is(0L));
    ClockUtil.reset();
}

93. TaskQueryTest#testFollowUpDateCombinations()

View license
@Deployment(resources = { "org/camunda/bpm/engine/test/api/task/TaskQueryTest.testProcessDefinition.bpmn20.xml" })
public void testFollowUpDateCombinations() throws ParseException {
    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");
    Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
    // Set follow-up date on task
    Date dueDate = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss").parse("01/02/2003 01:12:13");
    task.setFollowUpDate(dueDate);
    taskService.saveTask(task);
    Date oneHourAgo = new Date(dueDate.getTime() - 60 * 60 * 1000);
    Date oneHourLater = new Date(dueDate.getTime() + 60 * 60 * 1000);
    assertEquals(1, taskService.createTaskQuery().followUpAfter(oneHourAgo).followUpDate(dueDate).followUpBefore(oneHourLater).count());
    assertEquals(0, taskService.createTaskQuery().followUpAfter(oneHourLater).followUpDate(dueDate).followUpBefore(oneHourAgo).count());
    assertEquals(0, taskService.createTaskQuery().followUpAfter(oneHourLater).followUpDate(dueDate).count());
    assertEquals(0, taskService.createTaskQuery().followUpDate(dueDate).followUpBefore(oneHourAgo).count());
}

94. TaskQueryTest#testTaskDueDateCombinations()

View license
@Deployment(resources = { "org/camunda/bpm/engine/test/api/task/TaskQueryTest.testProcessDefinition.bpmn20.xml" })
public void testTaskDueDateCombinations() throws ParseException {
    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");
    Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
    // Set due-date on task
    Date dueDate = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss").parse("01/02/2003 01:12:13");
    task.setDueDate(dueDate);
    taskService.saveTask(task);
    Date oneHourAgo = new Date(dueDate.getTime() - 60 * 60 * 1000);
    Date oneHourLater = new Date(dueDate.getTime() + 60 * 60 * 1000);
    assertEquals(1, taskService.createTaskQuery().dueAfter(oneHourAgo).dueDate(dueDate).dueBefore(oneHourLater).count());
    assertEquals(0, taskService.createTaskQuery().dueAfter(oneHourLater).dueDate(dueDate).dueBefore(oneHourAgo).count());
    assertEquals(0, taskService.createTaskQuery().dueAfter(oneHourLater).dueDate(dueDate).count());
    assertEquals(0, taskService.createTaskQuery().dueDate(dueDate).dueBefore(oneHourAgo).count());
}

95. TaskQueryTest#testCreateTimeCombinations()

View license
public void testCreateTimeCombinations() throws ParseException {
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss.SSS");
    // Exact matching of createTime, should result in 6 tasks
    Date createTime = sdf.parse("01/01/2001 01:01:01.000");
    Date oneHourAgo = new Date(createTime.getTime() - 60 * 60 * 1000);
    Date oneHourLater = new Date(createTime.getTime() + 60 * 60 * 1000);
    assertEquals(6, taskService.createTaskQuery().taskCreatedAfter(oneHourAgo).taskCreatedOn(createTime).taskCreatedBefore(oneHourLater).count());
    assertEquals(0, taskService.createTaskQuery().taskCreatedAfter(oneHourLater).taskCreatedOn(createTime).taskCreatedBefore(oneHourAgo).count());
    assertEquals(0, taskService.createTaskQuery().taskCreatedAfter(oneHourLater).taskCreatedOn(createTime).count());
    assertEquals(0, taskService.createTaskQuery().taskCreatedOn(createTime).taskCreatedBefore(oneHourAgo).count());
}

96. AbstractInstanceManager#getStartAndEndDate()

Project: falcon
Source File: AbstractInstanceManager.java
View license
protected Pair<Date, Date> getStartAndEndDate(Entity entityObject, String startStr, String endStr, Integer numResults) throws FalconException {
    Pair<Date, Date> clusterStartEndDates = EntityUtil.getEntityStartEndDates(entityObject);
    Frequency frequency = EntityUtil.getFrequency(entityObject);
    Date endDate = getEndDate(endStr, clusterStartEndDates.second);
    Date startDate = getStartDate(startStr, endDate, clusterStartEndDates.first, frequency, numResults);
    if (startDate.after(endDate)) {
        throw new IllegalArgumentException("Specified End date " + SchemaHelper.getDateFormat().format(endDate) + " is before the entity was scheduled " + SchemaHelper.getDateFormat().format(startDate));
    }
    return new Pair<>(startDate, endDate);
}

97. BaseEntityUnitTests#testSetCreated()

Project: genie
Source File: BaseEntityUnitTests.java
View license
/**
     * Test to make sure the setter of created does nothing relative to persistence.
     */
@Test
public void testSetCreated() {
    final BaseEntity a = new BaseEntity();
    Assert.assertNotNull(a.getCreated());
    final Date date = new Date(0);
    a.setCreated(date);
    Assert.assertNotNull(a.getCreated());
    Assert.assertEquals(date, a.getCreated());
    a.onCreateBaseEntity();
    Assert.assertNotNull(a.getCreated());
    Assert.assertNotEquals(date, a.getCreated());
    final BaseEntity b = new BaseEntity();
    final Date created = b.getCreated();
    final Date newCreated = new Date(created.getTime() + 1);
    b.setCreated(newCreated);
    Assert.assertThat(b.getCreated(), Matchers.is(created));
}

98. ApnsFeedbackParsingUtils#checkParsedThree()

View license
public static void checkParsedThree(Map<String, Date> threeParsed) {
    Date d1 = new Date(firstDate * 1000L);
    String dt1 = Utilities.encodeHex(firstDevice);
    Date d2 = new Date(secondDate * 1000L);
    String dt2 = Utilities.encodeHex(secondDevice);
    Date d3 = new Date(thirdDate * 1000L);
    String dt3 = Utilities.encodeHex(thirdDevice);
    assertEquals(3, threeParsed.size());
    assertThat(threeParsed.keySet(), hasItems(dt1, dt2, dt3));
    assertEquals(d1, threeParsed.get(dt1));
    assertEquals(d2, threeParsed.get(dt2));
    assertEquals(d3, threeParsed.get(dt3));
}

99. ProxyContractComparator#compare()

Project: fqms
Source File: ProxyContractComparator.java
View license
@Override
public int compare(ProxyContract o1, ProxyContract o2) {
    Date time1;
    Date time2;
    try {
        time1 = new SimpleDateFormat("yyyy-MM-dd").parse(o1.getCommitTime());
        time2 = new SimpleDateFormat("yyyy-MM-dd").parse(o2.getCommitTime());
    } catch (ParseException e) {
        throw new RuntimeException(e);
    }
    return time1.compareTo(time2);
}

100. ExpBackoffPolicy#getDelay()

Project: falcon
Source File: ExpBackoffPolicy.java
View license
@Override
public long getDelay(Frequency delay, Date nominalTime, Date cutOffTime) throws FalconException {
    ExpressionHelper evaluator = ExpressionHelper.get();
    Date now = new Date();
    Date lateTime = nominalTime;
    long delayMilliSeconds = evaluator.evaluate(delay.toString(), Long.class);
    int factor = 1;
    // TODO we can get rid of this using formula
    while (lateTime.compareTo(now) <= 0) {
        lateTime = addTime(lateTime, (int) (factor * delayMilliSeconds));
        factor *= getPower();
    }
    if (lateTime.after(cutOffTime)) {
        lateTime = cutOffTime;
    }
    return (lateTime.getTime() - nominalTime.getTime());
}