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. 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;
}

6. 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);
}

7. 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();
}

8. 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();
    }
}

9. 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("");
}

10. 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));
}

11. 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));
}

12. 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));
}

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. 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));
}

15. 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);
}

16. 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()));
}

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. 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);
}

24. 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);
}

25. 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);
    }
}

26. 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;
}

27. 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;
}

28. 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));
}

29. 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)");
}

30. 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());
}

31. 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 } };
}

32. 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);
}

33. 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());
}

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. 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());
}

37. 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));
}

38. 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);
}

39. 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();
}

40. 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));
}

41. 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));
}

42. 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());
}

43. 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);
}

44. 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);
}

45. 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);
}

46. 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);
}

47. 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();
}

48. ElementDateComparator#compare()

View license
@Override
public int compare(final Object o1, final Object o2) {
    final Date d1 = getDate(o1);
    final Date d2 = getDate(o2);
    if (d1 == null) {
        return d2 == null ? 0 : -1;
    }
    if (d2 == null) {
        return 1;
    }
    return d1.compareTo(d2);
}

49. 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);
}

50. 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);
}

51. CalendarPickerViewTest#testSelectedNotInRange()

View license
@Test
public void testSelectedNotInRange() throws Exception {
    final Date minDate = today.getTime();
    today.add(YEAR, 1);
    final Date maxDate = today.getTime();
    today.add(YEAR, 1);
    Date selectedDate = today.getTime();
    try {
        //
        view.init(minDate, maxDate, locale).inMode(//
        SINGLE).withSelectedDate(selectedDate);
        fail("Should not have been able to pass in a selectedDate > maxDate");
    } catch (IllegalArgumentException expected) {
    }
    today.add(YEAR, -5);
    selectedDate = today.getTime();
    try {
        //
        view.init(minDate, maxDate, locale).inMode(//
        SINGLE).withSelectedDate(selectedDate);
        fail("Should not have been able to pass in a selectedDate < minDate");
    } catch (IllegalArgumentException expected) {
    }
}

52. StringDerivedPropertyTest#testCalendar()

View license
@Test
public void testCalendar() {
    Date now = new Date();
    StringDerivedProperty<Date> calendarProperty = new StringDerivedProperty<Date>("myproperty", now, new Function<String, Date>() {

        @Override
        public Date apply(@Nullable String input) {
            Date d = new Date();
            try {
                d.setTime(Long.parseLong(input));
            } catch (Exception e) {
                return new Date(0);
            }
            return d;
        }
    });
    assertEquals(now, calendarProperty.getValue());
    Date newTime = new Date();
    newTime.setTime(now.getTime() + 60000);
    ConfigurationManager.getConfigInstance().setProperty("myproperty", String.valueOf(newTime.getTime()));
    assertEquals(newTime, calendarProperty.getValue());
}

53. DateAssert_with_string_based_date_representation_Test#date_assertion_using_default_date_string_representation()

View license
@Test
public void date_assertion_using_default_date_string_representation() {
    // datetime with ms is supported
    final Date date1timeWithMS = parseDatetimeWithMs("2003-04-26T03:01:02.999");
    assertThat(date1timeWithMS).isEqualTo("2003-04-26T03:01:02.999");
    // datetime without ms is supported
    final Date datetime = parseDatetime("2003-04-26T03:01:02");
    assertThat(datetime).isEqualTo("2003-04-26T03:01:02.000");
    assertThat(datetime).isEqualTo("2003-04-26T03:01:02");
    // date is supported
    final Date date = DateUtil.parse("2003-04-26");
    assertThat(date).isEqualTo("2003-04-26");
    assertThat(date).isEqualTo("2003-04-26T00:00:00");
    assertThat(date).isEqualTo("2003-04-26T00:00:00.000");
}

54. Dates_assertIsEqualWithPrecision_Test#should_fail_if_hour_fields_differ_but_are_equal_when_am_pm_not_taken_into_account()

View license
@Test
public void should_fail_if_hour_fields_differ_but_are_equal_when_am_pm_not_taken_into_account() {
    AssertionInfo info = someInfo();
    final Date now = new Date();
    // build date differing only by AM/PM value 18 = 6PM <-> 6AM
    Calendar calendar1 = Calendar.getInstance();
    calendar1.setTime(now);
    calendar1.set(Calendar.HOUR_OF_DAY, 18);
    Calendar calendar2 = Calendar.getInstance();
    calendar2.setTime(now);
    calendar2.set(Calendar.HOUR_OF_DAY, 6);
    Date date1 = calendar1.getTime();
    Date date2 = calendar2.getTime();
    try {
        dates.assertIsEqualWithPrecision(info, date1, date2, TimeUnit.MINUTES);
    } catch (AssertionError e) {
        verify(failures).failure(info, shouldBeEqual(date1, date2, TimeUnit.MINUTES));
        return;
    }
    failBecauseExpectedAssertionErrorWasNotThrown();
}

55. DateUtilsTest#formatIso8601Date()

Project: aws-sdk-java
Source File: DateUtilsTest.java
View license
@Test
public void formatIso8601Date() throws ParseException {
    Date date = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    sdf.setTimeZone(new SimpleTimeZone(0, "GMT"));
    String expected = sdf.format(date);
    String actual = DateUtils.formatISO8601Date(date);
    assertEquals(expected, actual);
    Date expectedDate = sdf.parse(expected);
    Date actualDate = DateUtils.parseISO8601Date(actual);
    assertEquals(expectedDate, actualDate);
}

56. DateUtilsTest#formatRfc822Date()

Project: aws-sdk-java
Source File: DateUtilsTest.java
View license
@Test
public void formatRfc822Date() throws ParseException {
    Date date = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
    sdf.setTimeZone(new SimpleTimeZone(0, "GMT"));
    String expected = sdf.format(date);
    String actual = DateUtils.formatRFC822Date(date);
    assertEquals(expected, actual);
    Date expectedDate = sdf.parse(expected);
    Date actualDate = DateUtils.parseRFC822Date(actual);
    assertEquals(expectedDate, actualDate);
}

57. DateUtilsTest#parseIso8601Date()

Project: aws-sdk-java
Source File: DateUtilsTest.java
View license
@Test
public void parseIso8601Date() throws ParseException {
    Date date = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    sdf.setTimeZone(new SimpleTimeZone(0, "GMT"));
    String formatted = sdf.format(date);
    String alternative = DateUtils.iso8601DateFormat.print(date.getTime());
    assertEquals(formatted, alternative);
    Date expectedDate = sdf.parse(formatted);
    Date actualDate = DateUtils.parseISO8601Date(formatted);
    assertEquals(expectedDate, actualDate);
}

58. DateUtilsTest#parseIso8601Date_usingAlternativeFormat()

Project: aws-sdk-java
Source File: DateUtilsTest.java
View license
@Test
public void parseIso8601Date_usingAlternativeFormat() throws ParseException {
    Date date = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
    sdf.setTimeZone(new SimpleTimeZone(0, "GMT"));
    String formatted = sdf.format(date);
    String alternative = DateUtils.alternateIso8601DateFormat.print(date.getTime());
    assertEquals(formatted, alternative);
    Date expectedDate = sdf.parse(formatted);
    Date actualDate = DateUtils.parseISO8601Date(formatted);
    assertEquals(expectedDate, actualDate);
}

59. EntryGuards#needsUnreachableTest()

Project: bitcoinj
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);
}

60. SimulatedSSLSocket#connect()

View license
@Override
public void connect(SocketAddress endpoint, int timeout) throws IOException {
    Date start = new Date();
    socket.connect(endpoint, timeout);
    Date end = new Date();
    RequestInfo.get().connect(start, end);
    handshakeStart = new Date();
    startHandshake();
    this.addHandshakeCompletedListener(new HandshakeCompletedListener() {

        @Override
        public void handshakeCompleted(HandshakeCompletedEvent handshakeCompletedEvent) {
            if (handshakeStart != null) {
                RequestInfo.get().ssl(handshakeStart, new Date());
            }
        }
    });
}

61. 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());
}

62. 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());
}

63. 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());
}

64. 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();
}

65. 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();
}

66. 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);
}

67. 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);
}

68. 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);
}

69. CompareUtilTest#testDateNotInAnAscendingOrder()

View license
@Test
public void testDateNotInAnAscendingOrder() {
    Calendar calendar = Calendar.getInstance();
    calendar.set(2015, Calendar.MARCH, 15);
    Date first = calendar.getTime();
    calendar.set(2015, Calendar.AUGUST, 15);
    Date second = calendar.getTime();
    Date nullDate = null;
    assertThat(CompareUtil.areNotInAscendingOrder(null, first, null, second), is(false));
    assertThat(CompareUtil.areNotInAscendingOrder(null, first, null, first), is(false));
    assertThat(CompareUtil.areNotInAscendingOrder(null, second, null, first), is(true));
    assertThat(CompareUtil.areNotInAscendingOrder(nullDate, nullDate, nullDate), is(false));
    assertThat(CompareUtil.areNotInAscendingOrder(Arrays.asList(first, second)), is(false));
    assertThat(CompareUtil.areNotInAscendingOrder(Arrays.asList(first, first)), is(false));
    assertThat(CompareUtil.areNotInAscendingOrder(Arrays.asList(second, first)), is(true));
}

70. CustomBirthDateValidator#validate()

View license
/**
     * @see org.apache.cocoon.forms.validation.WidgetValidator#validate(org.apache.cocoon.forms.formmodel.Widget)
     */
public boolean validate(Widget widget) {
    Date birthDate = (Date) widget.getValue();
    if (getLogger().isDebugEnabled()) {
        getLogger().debug("Validating date " + birthDate);
    }
    GregorianCalendar cal = new GregorianCalendar();
    cal.add(Calendar.YEAR, -5);
    Date maxDate = cal.getTime();
    cal.add(Calendar.YEAR, -95);
    Date minDate = cal.getTime();
    if (birthDate.after(maxDate) || birthDate.before(minDate)) {
        if (widget instanceof ValidationErrorAware) {
            ((ValidationErrorAware) widget).setValidationError(new ValidationError("Invalid birth date", false));
        }
        return false;
    }
    return true;
}

71. TestDataConfiguration#testGetDateArrayWithFormat()

View license
@Test
public void testGetDateArrayWithFormat() throws Exception {
    DateFormat format = new SimpleDateFormat("MM/dd/yyyy");
    Date date1 = format.parse("01/01/2004");
    Date date2 = format.parse("12/31/2004");
    Date[] expected = new Date[] { date1, date2 };
    conf.addProperty("date.format", "01/01/2004");
    conf.addProperty("date.format", "12/31/2004");
    ArrayAssert.assertEquals("Wrong dates with format", expected, conf.getDateArray("date.format", "MM/dd/yyyy"));
}

72. ObjectUtilsTest#testMax()

Project: commons-lang
Source File: ObjectUtilsTest.java
View license
@Test
public void testMax() {
    final Calendar calendar = Calendar.getInstance();
    final Date nonNullComparable1 = calendar.getTime();
    final Date nonNullComparable2 = calendar.getTime();
    final String[] nullAray = null;
    calendar.set(Calendar.YEAR, calendar.get(Calendar.YEAR) - 1);
    final Date minComparable = calendar.getTime();
    assertNotSame(nonNullComparable1, nonNullComparable2);
    assertNull(ObjectUtils.max((String) null));
    assertNull(ObjectUtils.max(nullAray));
    assertSame(nonNullComparable1, ObjectUtils.max(null, nonNullComparable1));
    assertSame(nonNullComparable1, ObjectUtils.max(nonNullComparable1, null));
    assertSame(nonNullComparable1, ObjectUtils.max(null, nonNullComparable1, null));
    assertSame(nonNullComparable1, ObjectUtils.max(nonNullComparable1, nonNullComparable2));
    assertSame(nonNullComparable2, ObjectUtils.max(nonNullComparable2, nonNullComparable1));
    assertSame(nonNullComparable1, ObjectUtils.max(nonNullComparable1, minComparable));
    assertSame(nonNullComparable1, ObjectUtils.max(minComparable, nonNullComparable1));
    assertSame(nonNullComparable1, ObjectUtils.max(null, minComparable, null, nonNullComparable1));
    assertNull(ObjectUtils.max((String) null, (String) null));
}

73. ObjectUtilsTest#testMin()

Project: commons-lang
Source File: ObjectUtilsTest.java
View license
@Test
public void testMin() {
    final Calendar calendar = Calendar.getInstance();
    final Date nonNullComparable1 = calendar.getTime();
    final Date nonNullComparable2 = calendar.getTime();
    final String[] nullAray = null;
    calendar.set(Calendar.YEAR, calendar.get(Calendar.YEAR) - 1);
    final Date minComparable = calendar.getTime();
    assertNotSame(nonNullComparable1, nonNullComparable2);
    assertNull(ObjectUtils.min((String) null));
    assertNull(ObjectUtils.min(nullAray));
    assertSame(nonNullComparable1, ObjectUtils.min(null, nonNullComparable1));
    assertSame(nonNullComparable1, ObjectUtils.min(nonNullComparable1, null));
    assertSame(nonNullComparable1, ObjectUtils.min(null, nonNullComparable1, null));
    assertSame(nonNullComparable1, ObjectUtils.min(nonNullComparable1, nonNullComparable2));
    assertSame(nonNullComparable2, ObjectUtils.min(nonNullComparable2, nonNullComparable1));
    assertSame(minComparable, ObjectUtils.min(nonNullComparable1, minComparable));
    assertSame(minComparable, ObjectUtils.min(minComparable, nonNullComparable1));
    assertSame(minComparable, ObjectUtils.min(null, nonNullComparable1, null, minComparable));
    assertNull(ObjectUtils.min((String) null, (String) null));
}

74. CloningProviderTest#testValidCloneable()

View license
@Test
public void testValidCloneable() {
    final Date now = new Date();
    final CloningProvider<Date> provider = new CloningProvider<Date>(now);
    final Date clone1 = provider.getObject();
    assertEquals(now, clone1);
    assertNotSame(now, clone1);
    final Date clone2 = provider.getObject();
    assertEquals(now, clone2);
    assertNotSame(now, clone2);
    assertNotSame(clone2, clone1);
}

75. TestRecordWriterManager#testConstructorAndGetters()

View license
@Test
public void testConstructorAndGetters() throws Exception {
    RecordWriterManager mgr = managerBuilder().dirPathTemplate(getTestDir().toString() + "/${YYYY()}/${YY()}/${MM()}/${DD()}/${hh()}/${mm()}/${ss()}/" + "${not empty record:value('/') ? record:value('/') : 'blah'}").cutOffSecs(10).build();
    Date date = getFixedDate();
    Record record = RecordCreator.create();
    record.set(Field.create("a"));
    Assert.assertEquals(getTestDir() + "/2015/15/01/20/09/56/01/a", mgr.getDirPath(date, record));
    record.set(null);
    Assert.assertEquals(getTestDir() + "/2015/15/01/20/09/56/01/blah", mgr.getDirPath(date, record));
    Date now = date;
    Date recordDate = new Date(now.getTime() - 3000);
    Assert.assertEquals(7999, mgr.getTimeToLiveMillis(now, recordDate));
}

76. PasswordUtil#isPwdExpired()

Project: directory-shared
Source File: PasswordUtil.java
View license
/**
     * checks if the given password's change time is older than the max age 
     *
     * @param pwdChangedZtime time when the password was last changed
     * @param pwdMaxAgeSec the max age value in seconds
     * @return true if expired, false otherwise
     */
public static boolean isPwdExpired(String pwdChangedZtime, int pwdMaxAgeSec) {
    Date pwdChangeDate = DateUtils.getDate(pwdChangedZtime);
    //DIRSERVER-1735
    long time = pwdMaxAgeSec * 1000L;
    time += pwdChangeDate.getTime();
    Date expiryDate = DateUtils.getDate(DateUtils.getGeneralizedTime(time));
    Date now = DateUtils.getDate(DateUtils.getGeneralizedTime());
    boolean expired = false;
    if (expiryDate.equals(now) || expiryDate.before(now)) {
        expired = true;
    }
    return expired;
}

77. TestScheduleComputeHelper#checkCorrect()

View license
public void checkCorrect(ScheduleSpec spec, String now, String expected) throws Exception {
    Date nowDate = timeFormat.parse(now);
    Date expectedDate = timeFormat.parse(expected);
    long result = ScheduleComputeHelper.computeNextOccurance(spec, nowDate.getTime(), TimeZone.getDefault());
    Date resultDate = new Date(result);
    if (!(resultDate.equals(expectedDate))) {
        log.debug(".checkCorrect Difference in result found, spec=" + spec);
        log.debug(".checkCorrect      now=" + timeFormat.format(nowDate) + " long=" + nowDate.getTime());
        log.debug(".checkCorrect expected=" + timeFormat.format(expectedDate) + " long=" + expectedDate.getTime());
        log.debug(".checkCorrect   result=" + timeFormat.format(resultDate) + " long=" + resultDate.getTime());
        assertTrue(false);
    }
}

78. 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);
}

79. 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());
}

80. 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);
}

81. ApiProxyOrderController#analyizeChildOrder()

Project: fqms
Source File: ApiProxyOrderController.java
View license
/**
     * ????????
     * @param childJson ???json
     * @return ???
     */
private ProxyOrder analyizeChildOrder(JSONObject childJson) {
    BigDecimal bookRoomPrice = childJson.getBigDecimal("bookRoomPrice");
    Date checkInAt = childJson.getDate("checkInAt");
    Date checkOutAt = childJson.getDate("checkOutAt");
    Integer roomTypeId = childJson.getInteger("roomTypeId");
    String roomTypeName = childJson.getString("roomTypeName");
    if (!(bookRoomPrice.compareTo(new BigDecimal(0)) > 0)) {
        throw new RuntimeException("???????0");
    }
    if (checkInAt.after(checkOutAt)) {
        throw new RuntimeException("???????????");
    }
    if (StringUtils.isBlank(roomTypeName) || roomTypeId == null) {
        throw new RuntimeException("??ID???????");
    }
    ProxyOrder proxyOrder = new ProxyOrder();
    proxyOrder.setBookRoomPrice(bookRoomPrice);
    proxyOrder.setCheckInAt(checkInAt);
    proxyOrder.setCheckOutAt(checkOutAt);
    proxyOrder.setRoomTypeId(roomTypeId);
    proxyOrder.setRoomTypeName(roomTypeName);
    proxyOrder.setId(ProxyOrderIdGenerator.generate());
    return proxyOrder;
}

82. UpdateCheckAction#setTimer()

Project: freeplane
Source File: UpdateCheckAction.java
View license
private void setTimer() {
    if (autorunEnabled == false) {
        return;
    }
    autorunEnabled = ResourceController.getResourceController().getBooleanProperty(CHECK_UPDATES_AUTOMATICALLY);
    if (autorunEnabled == false) {
        return;
    }
    autorunEnabled = false;
    final Date now = new Date();
    final long nextCheckMillis = ResourceController.getResourceController().getLongProperty(LAST_UPDATE_CHECK_TIME, 0) + TWO_DAYS;
    final Date nextCheckDate = new Date(nextCheckMillis);
    if (now.before(nextCheckDate)) {
        final FreeplaneVersion knownNewVersion = getKnownNewVersion();
        addUpdateButton(knownNewVersion);
        return;
    }
    autorunTimer = new Timer(CHECK_TIME, this);
    autorunTimer.setRepeats(false);
    autorunTimer.start();
}

83. 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));
}

84. 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));
}

85. JournalEntryWritePlatformServiceJpaRepositoryImpl#validateBusinessRulesForJournalEntries()

View license
private void validateBusinessRulesForJournalEntries(final JournalEntryCommand command) {
    /** check if date of Journal entry is valid ***/
    final LocalDate entryLocalDate = command.getTransactionDate();
    final Date transactionDate = entryLocalDate.toDateTimeAtStartOfDay().toDate();
    // shouldn't be in the future
    final Date todaysDate = new Date();
    if (transactionDate.after(todaysDate)) {
        throw new JournalEntryInvalidException(GL_JOURNAL_ENTRY_INVALID_REASON.FUTURE_DATE, transactionDate, null, null);
    }
    // shouldn't be before an accounting closure
    final GLClosure latestGLClosure = this.glClosureRepository.getLatestGLClosureByBranch(command.getOfficeId());
    if (latestGLClosure != null) {
        if (latestGLClosure.getClosingDate().after(transactionDate) || latestGLClosure.getClosingDate().equals(transactionDate)) {
            throw new JournalEntryInvalidException(GL_JOURNAL_ENTRY_INVALID_REASON.ACCOUNTING_CLOSED, latestGLClosure.getClosingDate(), null, null);
        }
    }
    /*** check if credits and debits are valid **/
    final SingleDebitOrCreditEntryCommand[] credits = command.getCredits();
    final SingleDebitOrCreditEntryCommand[] debits = command.getDebits();
    // atleast one debit or credit must be present
    if (credits == null || credits.length <= 0 || debits == null || debits.length <= 0) {
        throw new JournalEntryInvalidException(GL_JOURNAL_ENTRY_INVALID_REASON.NO_DEBITS_OR_CREDITS, null, null, null);
    }
    checkDebitAndCreditAmounts(credits, debits);
}

86. 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);
}

87. PerformanceLog#getTime()

View license
String getTime(String t1, String t2) {
    Date d1 = null;
    Date d2 = null;
    SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
    try {
        d1 = sdf.parse(t1);
        d2 = sdf.parse(t2);
    } catch (ParseException pe) {
        System.out.println("error");
    }
    if (d2.getTime() > d1.getTime())
        System.out.println("Incorrect performance log");
    Date d = new Date(d1.getTime() - d2.getTime());
    char strs[] = sdf.format(d).toCharArray();
    strs[0] = '0';
    strs[1] = '0';
    return new String(strs);
}

88. DateTest#test_ConstructorIII()

Project: j2objc
Source File: DateTest.java
View license
/**
	 * @tests java.util.Date#Date(int, int, int)
	 */
public void test_ConstructorIII() {
    // Test for method java.util.Date(int, int, int)
    // the epoch + local time
    Date d1 = new Date(70, 0, 1);
    // the epoch + local time
    Date d2 = new Date(0 + d1.getTimezoneOffset() * 60 * 1000);
    assertTrue("Created incorrect date", d1.equals(d2));
    Date date = new Date(99, 5, 22);
    Calendar cal = new GregorianCalendar(1999, Calendar.JUNE, 22);
    assertTrue("Wrong time zone", date.equals(cal.getTime()));
}

89. 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));
}

90. 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;
}

91. 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());
}

92. 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());
}

93. 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;
}

94. 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;
}

95. 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));
}

96. 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);
}

97. 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));
}

98. 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()));
}

99. 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);
}

100. 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);
}