Java Code Examples for javax.xml.datatype.Duration

The following are top voted examples for showing how to use javax.xml.datatype.Duration. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: openjdk-jdk10   File: DurationTest.java   Source Code and License 6 votes vote down vote up
@DataProvider(name = "duration-field")
public Object[][] getDurationAndField() {
    Function<Duration, Integer> getyears = duration -> duration.getYears();
    Function<Duration, Integer> getmonths = duration -> duration.getMonths();
    Function<Duration, Integer> getdays = duration -> duration.getDays();
    Function<Duration, Integer> gethours = duration -> duration.getHours();
    Function<Duration, Integer> getminutes = duration -> duration.getMinutes();
    Function<Duration, Integer> getseconds = duration -> duration.getSeconds();
    return new Object[][] {
            { "P1Y1M1DT1H1M1S", getyears, 1 },
            { "P1M1DT1H1M1S", getyears, 0 },
            { "P1Y1M1DT1H1M1S", getmonths, 1 },
            { "P1Y1DT1H1M1S", getmonths, 0 },
            { "P1Y1M1DT1H1M1S", getdays, 1 },
            { "P1Y1MT1H1M1S", getdays, 0 },
            { "P1Y1M1DT1H1M1S", gethours, 1 },
            { "P1Y1M1DT1M1S", gethours, 0 },
            { "P1Y1M1DT1H1M1S", getminutes, 1 },
            { "P1Y1M1DT1H1S", getminutes, 0 },
            { "P1Y1M1DT1H1M1S", getseconds, 1 },
            { "P1Y1M1DT1H1M", getseconds, 0 },
            { "P1Y1M1DT1H1M100000000S", getseconds, 100000000 }, };
}
 
Example 2
Project: openjdk-jdk10   File: DurationTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testDurationAndCalendar1() {
    int year = 1;
    int month = 2;
    int day = 3;
    int hour = 4;
    int min = 5;
    int sec = 6;
    String lexicalRepresentation = "P" + year + "Y" + month + "M" + day + "DT" + hour + "H" + min + "M" + sec + "S";
    try {
        Duration dur = DatatypeFactory.newInstance().newDuration(lexicalRepresentation);
        System.out.println(dur.toString());
        AssertJUnit.assertTrue("year should be 1", dur.getYears() == year);
        AssertJUnit.assertTrue("month should be 2", dur.getMonths() == month);
        AssertJUnit.assertTrue("day should be 3", dur.getDays() == day);
        AssertJUnit.assertTrue("hour should be 4", dur.getHours() == hour);
        AssertJUnit.assertTrue("minute should be 5", dur.getMinutes() == min);
        AssertJUnit.assertTrue("second should be 6", dur.getSeconds() == sec);
    } catch (DatatypeConfigurationException e) {
        e.printStackTrace();
    }
}
 
Example 3
Project: OpenJSharp   File: XMLGregorianCalendarImpl.java   Source Code and License 6 votes vote down vote up
/**
     * <p>Normalize this instance to UTC.</p>
     *
     * <p>2000-03-04T23:00:00+03:00 normalizes to 2000-03-04T20:00:00Z</p>
     * <p>Implements W3C XML Schema Part 2, Section 3.2.7.3 (A).</p>
     */
private XMLGregorianCalendar normalizeToTimezone(int timezone) {

    int minutes = timezone;
    XMLGregorianCalendar result = (XMLGregorianCalendar) this.clone();

    // normalizing to UTC time negates the timezone offset before
    // addition.
    minutes = -minutes;
    Duration d = new DurationImpl(minutes >= 0, // isPositive
            0, //years
            0, //months
            0, //days
            0, //hours
            minutes < 0 ? -minutes : minutes, // absolute
            0  //seconds
    );
    result.add(d);

    // set to zulu UTC time.
    result.setTimezone(0);
    return result;
}
 
Example 4
Project: openjdk-jdk10   File: Bug6937964Test.java   Source Code and License 5 votes vote down vote up
@Test
public void testNewDurationYearMonthLexicalRepresentation() throws DatatypeConfigurationException {
    DatatypeFactory dtf = DatatypeFactory.newInstance();
    Duration d = dtf.newDurationYearMonth("P20Y15M");
    int years = d.getYears();
    Assert.assertTrue(years == 21, "Return value should be normalized");
}
 
Example 5
Project: tck   File: DroolsTCKTest.java   Source Code and License 5 votes vote down vote up
private boolean isDateTimeOrDuration(Object value)
{
   return value instanceof Duration || value instanceof XMLGregorianCalendar;
}
 
Example 6
Project: oscm   File: ObjectFactoryTest.java   Source Code and License 5 votes vote down vote up
private Object getInputArgument(Class<?> clazz,
        boolean testSettersAndGetters) throws Exception {

    if (clazz.isAssignableFrom(String.class)) {
        return new String("Dummy Value String");
    } else if (clazz.isAssignableFrom(XMLGregorianCalendar.class)) {
        return DatatypeFactory.newInstance().newXMLGregorianCalendar();
    } else if (clazz.isAssignableFrom(Boolean.class)) {
        return new Boolean(true);
    } else if (clazz.isAssignableFrom(Integer.class)) {
        return new Integer(5);
    } else if (clazz.isAssignableFrom(BigInteger.class)) {
        return new BigInteger("5");
    } else if (clazz.isAssignableFrom(byte[].class)) {
        return new byte[5];
    } else if (clazz.isAssignableFrom(Duration.class)) {
        return DatatypeFactory.newInstance().newDuration(100L);
    } else if (clazz.isEnum()) {
        return clazz.getEnumConstants()[0];
    } else {
        Object typeObject = createTypeFromObjectFactory(clazz);
        if (testSettersAndGetters) {
            testSettersAndGetters(typeObject);
        }
        return typeObject;
    }
}
 
Example 7
Project: openjdk-jdk10   File: DayTimeDurationDV.java   Source Code and License 5 votes vote down vote up
protected Duration getDuration(DateTimeData date) {
    int sign = 1;
    if (date.day<0 || date.hour<0 || date.minute<0 || date.second<0) {
        sign = -1;
    }
    return datatypeFactory.newDuration(sign == 1, null, null,
            date.day != DatatypeConstants.FIELD_UNDEFINED?BigInteger.valueOf(sign*date.day):null,
            date.hour != DatatypeConstants.FIELD_UNDEFINED?BigInteger.valueOf(sign*date.hour):null,
            date.minute != DatatypeConstants.FIELD_UNDEFINED?BigInteger.valueOf(sign*date.minute):null,
            date.second != DatatypeConstants.FIELD_UNDEFINED?new BigDecimal(String.valueOf(sign*date.second)):null);
}
 
Example 8
Project: lemon   File: DurationUtil.java   Source Code and License 5 votes vote down vote up
private Date add(Date date, Duration duration) {
    if (!useBusinessTime) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        duration.addTo(calendar);

        return calendar.getTime();
    }

    return businessCalendar.add(date, duration, useBusinessTime);
}
 
Example 9
Project: java-kdb-communication   File: Converters.java   Source Code and License 5 votes vote down vote up
/** @return kdb {@link Timespan} equivalent to XML duration */
public static Timespan durationToTimespan(Duration xmlDuration) {
	if(xmlDuration == null)
		return new Timespan(0l);
	
	return new Timespan(NANO_SECONDS_IN_1_MS * xmlDuration.getTimeInMillis(DateTime.now().toDate()));
}
 
Example 10
Project: openjdk-jdk10   File: Bug6937964Test.java   Source Code and License 5 votes vote down vote up
@Test
public void testNewDurationYearMonthMilliseconds() throws DatatypeConfigurationException {
    DatatypeFactory dtf = DatatypeFactory.newInstance();
    Duration d = dtf.newDurationYearMonth(671976000000L);
    int years = d.getYears();
    System.out.println("Years: " + years);
    Assert.assertTrue(years == 21, "Return value should be normalized");
}
 
Example 11
Project: openjdk-jdk10   File: YearMonthDurationDV.java   Source Code and License 5 votes vote down vote up
protected Duration getDuration(DateTimeData date) {
    int sign = 1;
    if ( date.year<0 || date.month<0) {
        sign = -1;
    }
    return datatypeFactory.newDuration(sign == 1,
            date.year != DatatypeConstants.FIELD_UNDEFINED?BigInteger.valueOf(sign*date.year):null,
            date.month != DatatypeConstants.FIELD_UNDEFINED?BigInteger.valueOf(sign*date.month):null,
            null,
            null,
            null,
            null);
}
 
Example 12
Project: openjdk-jdk10   File: DurationTest.java   Source Code and License 5 votes vote down vote up
@Test(dataProvider = "duration-for-add")
public void checkDurationAdd(String initVal, String addVal, String result) {
    Duration durationInit = datatypeFactory.newDuration(initVal);
    Duration durationAdd = datatypeFactory.newDuration(addVal);
    Duration durationResult = datatypeFactory.newDuration(result);

    assertEquals(durationInit.add(durationAdd), durationResult);
}
 
Example 13
Project: openjdk-jdk10   File: DurationTest.java   Source Code and License 5 votes vote down vote up
@Test(dataProvider = "number-string")
public void checkDurationToString(boolean isPositive, int years, int months, int days, int hours, int minutes, int seconds, String lexical) {
    Duration duration = datatypeFactory.newDuration(isPositive,  years,  months,  days,  hours,  minutes,  seconds);
    assertEquals(duration.toString(), lexical);

    assertEquals(datatypeFactory.newDuration(duration.toString()), duration);
}
 
Example 14
Project: openjdk-jdk10   File: DurationImpl.java   Source Code and License 5 votes vote down vote up
/**
 * <p>Converts the years and months fields into the days field
 * by using a specific time instant as the reference point.</p>
 *
 * <p>For example, duration of one month normalizes to 31 days
 * given the start time instance "July 8th 2003, 17:40:32".</p>
 *
 * <p>Formally, the computation is done as follows:</p>
 * <ol>
 *  <li>The given Calendar object is cloned.
 *  <li>The years, months and days fields will be added to
 *      the {@link Calendar} object
 *      by using the {@link Calendar#add(int,int)} method.
 *  <li>The difference between two Calendars are computed in terms of days.
 *  <li>The computed days, along with the hours, minutes and seconds
 *      fields of this duration object is used to construct a new
 *      Duration object.
 * </ol>
 *
 * <p>Note that since the Calendar class uses <code>int</code> to
 * hold the value of year and month, this method may produce
 * an unexpected result if this duration object holds
 * a very large value in the years or months fields.</p>
 *
 * @param startTimeInstant <code>Calendar</code> reference point.
 *
 * @return <code>Duration</code> of years and months of this <code>Duration</code> as days.
 *
 * @throws NullPointerException If the startTimeInstant parameter is null.
 */
public Duration normalizeWith(Calendar startTimeInstant) {

    Calendar c = (Calendar) startTimeInstant.clone();

    // using int may cause overflow, but
    // Calendar internally treats value as int anyways.
    c.add(Calendar.YEAR, getYears() * signum);
    c.add(Calendar.MONTH, getMonths() * signum);
    c.add(Calendar.DAY_OF_MONTH, getDays() * signum);

    // obtain the difference in terms of days
    long diff = getCalendarTimeInMillis(c) - getCalendarTimeInMillis(startTimeInstant);
    int days = (int) (diff / (1000L * 60L * 60L * 24L));

    return new DurationImpl(
            days >= 0,
            null,
            null,
            wrap(Math.abs(days)),
            (BigInteger) getField(DatatypeConstants.HOURS),
            (BigInteger) getField(DatatypeConstants.MINUTES),
            (BigDecimal) getField(DatatypeConstants.SECONDS));
}
 
Example 15
Project: openjdk-jdk10   File: Bug6937964Test.java   Source Code and License 5 votes vote down vote up
@Test
public void testNewDurationYearMonthBigInteger() throws DatatypeConfigurationException {
    DatatypeFactory dtf = DatatypeFactory.newInstance();
    BigInteger year = new BigInteger("20");
    BigInteger mon = new BigInteger("15");
    Duration d = dtf.newDurationYearMonth(true, year, mon);
    int years = d.getYears();
    Assert.assertTrue(years == 21, "Return value should be normalized");
}
 
Example 16
Project: openjdk-jdk10   File: DurationTest.java   Source Code and License 5 votes vote down vote up
@Test(dataProvider = "duration-fields")
public void checkDurationGetField(String lexRepresentation, BigInteger years, BigInteger months, BigInteger days, BigInteger hours, BigInteger minutes,
        BigDecimal seconds) {
    Duration duration = datatypeFactory.newDuration(lexRepresentation);

    assertEquals(duration.getField(YEARS), years);
    assertEquals(duration.getField(MONTHS), months);
    assertEquals(duration.getField(DAYS), days);
    assertEquals(duration.getField(HOURS), hours);
    assertEquals(duration.getField(MINUTES), minutes);
    assertEquals(duration.getField(SECONDS), seconds);
}
 
Example 17
Project: openjdk-jdk10   File: DurationTest.java   Source Code and License 5 votes vote down vote up
@Test
public void checkDurationNegate() {
    Duration durationPos = datatypeFactory.newDuration("P1Y0M0DT0H0M0S");
    Duration durationNeg = datatypeFactory.newDuration("-P1Y0M0DT0H0M0S");

    assertEquals(durationPos.negate(), durationNeg);
    assertEquals(durationNeg.negate(), durationPos);
    assertEquals(durationPos.negate().negate(), durationPos);

}
 
Example 18
Project: openjdk-jdk10   File: Bug6937964Test.java   Source Code and License 5 votes vote down vote up
@Test
public void testNewDurationDayTimeLexicalRepresentation() throws DatatypeConfigurationException {
    DatatypeFactory dtf = DatatypeFactory.newInstance();
    Duration d = dtf.newDurationDayTime("P1DT23H59M65S");
    int days = d.getDays();
    Assert.assertTrue(days == 2, "Return value should be normalized");
}
 
Example 19
Project: openjdk-jdk10   File: Bug6937964Test.java   Source Code and License 5 votes vote down vote up
@Test
public void testNewDurationDayTimeBigInteger() throws DatatypeConfigurationException {
    DatatypeFactory dtf = DatatypeFactory.newInstance();
    BigInteger day = new BigInteger("1");
    BigInteger hour = new BigInteger("23");
    BigInteger min = new BigInteger("59");
    BigInteger sec = new BigInteger("65");
    Duration d = dtf.newDurationDayTime(true, day, hour, min, sec);
    int days = d.getDays();
    System.out.println("Days: " + days);
    Assert.assertTrue(days == 2, "Return value should be normalized");
}
 
Example 20
Project: openjdk-jdk10   File: DurationTest.java   Source Code and License 5 votes vote down vote up
private void newDurationTester(boolean isPositive, boolean normalizedIsPositive, BigInteger years, BigInteger normalizedYears, BigInteger months,
        BigInteger normalizedMonths, BigInteger days, BigInteger normalizedDays, BigInteger hours, BigInteger normalizedHours, BigInteger minutes,
        BigInteger normalizedMinutes, BigDecimal seconds, BigDecimal normalizedSeconds, long durationInMilliSeconds, long normalizedDurationInMilliSeconds,
        String lexicalRepresentation, String normalizedLexicalRepresentation) {

    DatatypeFactory datatypeFactory = null;
    try {
        datatypeFactory = DatatypeFactory.newInstance();
    } catch (DatatypeConfigurationException ex) {
        ex.printStackTrace();
        Assert.fail(ex.toString());
    }

    // create 4 Durations using the 4 different constructors

    Duration durationBigInteger = datatypeFactory.newDuration(isPositive, years, months, days, hours, minutes, seconds);
    durationAssertEquals(durationBigInteger, DatatypeConstants.DURATION, normalizedIsPositive, normalizedYears.intValue(), normalizedMonths.intValue(),
            normalizedDays.intValue(), normalizedHours.intValue(), normalizedMinutes.intValue(), normalizedSeconds.intValue(),
            normalizedDurationInMilliSeconds, normalizedLexicalRepresentation);

    Duration durationInt = datatypeFactory.newDuration(isPositive, years.intValue(), months.intValue(), days.intValue(), hours.intValue(),
            minutes.intValue(), seconds.intValue());
    durationAssertEquals(durationInt, DatatypeConstants.DURATION, normalizedIsPositive, normalizedYears.intValue(), normalizedMonths.intValue(),
            normalizedDays.intValue(), normalizedHours.intValue(), normalizedMinutes.intValue(), normalizedSeconds.intValue(),
            normalizedDurationInMilliSeconds, normalizedLexicalRepresentation);

    Duration durationMilliseconds = datatypeFactory.newDuration(durationInMilliSeconds);
    durationAssertEquals(durationMilliseconds, DatatypeConstants.DURATION, normalizedIsPositive, normalizedYears.intValue(), normalizedMonths.intValue(),
            normalizedDays.intValue(), normalizedHours.intValue(), normalizedMinutes.intValue(), normalizedSeconds.intValue(),
            normalizedDurationInMilliSeconds, normalizedLexicalRepresentation);

    Duration durationLexical = datatypeFactory.newDuration(lexicalRepresentation);
    durationAssertEquals(durationLexical, DatatypeConstants.DURATION, normalizedIsPositive, normalizedYears.intValue(), normalizedMonths.intValue(),
            normalizedDays.intValue(), normalizedHours.intValue(), normalizedMinutes.intValue(), normalizedSeconds.intValue(),
            normalizedDurationInMilliSeconds, normalizedLexicalRepresentation);
}
 
Example 21
Project: OpenJSharp   File: DurationDV.java   Source Code and License 5 votes vote down vote up
protected Duration getDuration(DateTimeData date) {
    int sign = 1;
    if ( date.year<0 || date.month<0 || date.day<0
            || date.hour<0 || date.minute<0 || date.second<0) {
        sign = -1;
    }
    return datatypeFactory.newDuration(sign == 1,
            date.year != DatatypeConstants.FIELD_UNDEFINED?BigInteger.valueOf(sign*date.year):null,
            date.month != DatatypeConstants.FIELD_UNDEFINED?BigInteger.valueOf(sign*date.month):null,
            date.day != DatatypeConstants.FIELD_UNDEFINED?BigInteger.valueOf(sign*date.day):null,
            date.hour != DatatypeConstants.FIELD_UNDEFINED?BigInteger.valueOf(sign*date.hour):null,
            date.minute != DatatypeConstants.FIELD_UNDEFINED?BigInteger.valueOf(sign*date.minute):null,
            date.second != DatatypeConstants.FIELD_UNDEFINED?new BigDecimal(String.valueOf(sign*date.second)):null);
}
 
Example 22
Project: OpenJSharp   File: YearMonthDurationDV.java   Source Code and License 5 votes vote down vote up
protected Duration getDuration(DateTimeData date) {
    int sign = 1;
    if ( date.year<0 || date.month<0) {
        sign = -1;
    }
    return datatypeFactory.newDuration(sign == 1,
            date.year != DatatypeConstants.FIELD_UNDEFINED?BigInteger.valueOf(sign*date.year):null,
            date.month != DatatypeConstants.FIELD_UNDEFINED?BigInteger.valueOf(sign*date.month):null,
            null,
            null,
            null,
            null);
}
 
Example 23
Project: openjdk-jdk10   File: JDK8068839Test.java   Source Code and License 5 votes vote down vote up
@Test
public void test() throws DatatypeConfigurationException {
    DatatypeFactory df = DatatypeFactory.newInstance();
    Duration durationx = df.newDuration(Long.MIN_VALUE);
    Assert.assertEquals(durationx.toString(), "-P292277024Y7M16DT7H12M55.808S");
    durationx = df.newDuration(Long.MAX_VALUE);
    Assert.assertEquals(durationx.toString(), "P292277024Y7M16DT7H12M55.807S");
}
 
Example 24
Project: openjdk-jdk10   File: SerializationTest.java   Source Code and License 5 votes vote down vote up
/**
 * Create test files
 *
 * @param javaVersion JDK version
 */
public void createTestFile(String javaVersion) {
    try {
        DatatypeFactory dtf = DatatypeFactory.newInstance();
        XMLGregorianCalendar c = dtf.newXMLGregorianCalendar(EXPECTED_CAL);
        Duration d = dtf.newDuration(EXPECTED_DURATION);
        toFile((Serializable) c, filePath + javaVersion + FILENAME_CAL);
        toFile((Serializable) d, filePath + javaVersion + FILENAME_DURATION);
    } catch (Exception e) {
        fail(e.getMessage());
    }
}
 
Example 25
Project: openjdk-jdk10   File: DurationTest.java   Source Code and License 5 votes vote down vote up
@Test(dataProvider = "duration-for-hash")
public void checkDurationHashCode(String lexRepresentation1, String lexRepresentation2) {
    Duration duration1 = datatypeFactory.newDuration(lexRepresentation1);
    Duration duration2 = datatypeFactory.newDuration(lexRepresentation2);
    int hash1 = duration1.hashCode();
    int hash2 = duration2.hashCode();
    assertTrue(hash1 == hash2, " generated hash1 : " + hash1 + " generated hash2 : " + hash2);
}
 
Example 26
Project: openjdk-jdk10   File: DurationTest.java   Source Code and License 4 votes vote down vote up
@Test(dataProvider = "duration-field")
public void checkDurationGetOneField(String lexRepresentation, Function<Duration, Integer> getter, int value) {
    Duration duration = datatypeFactory.newDuration(lexRepresentation);
    assertEquals(getter.apply(duration).intValue(), value);
}
 
Example 27
Project: openjdk-jdk10   File: DurationTest.java   Source Code and License 4 votes vote down vote up
/**
 * Inspired by CR 5077522 Duration.compare makes mistakes for some values.
 */
@Test
public void testCompareWithInderterminateRelation() {

    final String[][] partialOrder = { // partialOrder
    { "P1Y", "<>", "P365D" }, { "P1Y", "<>", "P366D" }, { "P1M", "<>", "P28D" }, { "P1M", "<>", "P29D" }, { "P1M", "<>", "P30D" }, { "P1M", "<>", "P31D" },
            { "P5M", "<>", "P150D" }, { "P5M", "<>", "P151D" }, { "P5M", "<>", "P152D" }, { "P5M", "<>", "P153D" }, { "PT2419200S", "<>", "P1M" },
            { "PT2678400S", "<>", "P1M" }, { "PT31536000S", "<>", "P1Y" }, { "PT31622400S", "<>", "P1Y" }, { "PT525600M", "<>", "P1Y" },
            { "PT527040M", "<>", "P1Y" }, { "PT8760H", "<>", "P1Y" }, { "PT8784H", "<>", "P1Y" }, { "P365D", "<>", "P1Y" }, };

    DatatypeFactory df = null;
    try {
        df = DatatypeFactory.newInstance();
    } catch (DatatypeConfigurationException ex) {
        ex.printStackTrace();
        Assert.fail(ex.toString());
    }

    boolean compareErrors = false;

    for (int valueIndex = 0; valueIndex < partialOrder.length; ++valueIndex) {
        Duration duration1 = df.newDuration(partialOrder[valueIndex][0]);
        Duration duration2 = df.newDuration(partialOrder[valueIndex][2]);
        int cmp = duration1.compare(duration2);
        int expected = ">".equals(partialOrder[valueIndex][1]) ? DatatypeConstants.GREATER
                : "<".equals(partialOrder[valueIndex][1]) ? DatatypeConstants.LESSER : "==".equals(partialOrder[valueIndex][1]) ? DatatypeConstants.EQUAL
                        : DatatypeConstants.INDETERMINATE;

        // just note any errors, do not fail until all cases have been
        // tested
        if (expected != cmp) {
            compareErrors = true;
            System.err.println("returned " + cmp2str(cmp) + " for durations \'" + duration1 + "\' and " + duration2 + "\', but expected "
                    + cmp2str(expected));
        }
    }

    if (compareErrors) {
        // TODO; fix bug, these tests should pass
        if (false) {
            Assert.fail("Errors in comparing indeterminate relations, see Stderr");
        } else {
            System.err.println("Please fix this bug: " + "Errors in comparing indeterminate relations, see Stderr");
        }
    }
}
 
Example 28
Project: lemon   File: DurationUtil.java   Source Code and License 4 votes vote down vote up
private Duration parsePeriod(String period) throws Exception {
    return datatypeFactory.newDuration(period);
}
 
Example 29
Project: lemon   File: WorkCalendar.java   Source Code and License 4 votes vote down vote up
/**
 * 计算结束时间.
 */
public Date add(Date startDate, Duration duration) {
    // 得到对应的时间
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(startDate);
    // 添加年数和月数,工作日方面年和月的概念不会改变
    calendar.add(Calendar.YEAR, duration.getYears());
    calendar.add(Calendar.MONTH, duration.getMonths());

    // 天数,小时,分钟可能因为工作日有概念,所以特殊处理
    int day = duration.getDays();
    int hour = duration.getHours();
    int minute = duration.getMinutes();

    if (accurateToDay) {
        // 有时需要自动把一天换算成8个小时,以实际计算工时
        hour += (day * HOUR_OF_DAY);
        day = 0;
    } else {
        Date workDate = this.findWorkDate(calendar.getTime());
        calendar.setTime(workDate);

        // 目前还没有更好的算法,所以对天数累加,再判断是否工作日
        for (int i = 0; i < day; i++) {
            calendar.add(Calendar.DATE, 1);

            int originHour = calendar.get(Calendar.HOUR_OF_DAY);
            int originMinute = calendar.get(Calendar.MINUTE);
            // 如果当前就是工作日,就返回当前时间
            // 如果当前的时间已经不是工作日了就返回最近的工作日
            workDate = this.findWorkDate(calendar.getTime());
            calendar.setTime(workDate);
            calendar.set(Calendar.HOUR_OF_DAY, originHour);
            calendar.set(Calendar.MINUTE, originMinute);
        }
    }

    Date targetDate = calendar.getTime();
    long millis = (hour * MILLIS_OF_HOUR) + (minute * MILLIS_OF_MINUTE);
    DayPart dayPart = this.findDayPart(targetDate);
    boolean isInbusinessHours = (dayPart != null);

    if (!isInbusinessHours) {
        DayPartResult dayPartResult = this.findTargetWorkDay(targetDate)
                .findNextDayPartStart(0, targetDate);
        targetDate = dayPartResult.getDate();
        dayPart = dayPartResult.getDayPart();
    }

    Date end = dayPart.add(targetDate, millis);

    return end;
}
 
Example 30
Project: lemon   File: WorkCalendar.java   Source Code and License 4 votes vote down vote up
private Duration parsePeriod(String period) throws Exception {
    return datatypeFactory.newDuration(period);
}
 
Example 31
Project: lemon   File: WorkCalendarService.java   Source Code and License 4 votes vote down vote up
public Date add(Date date, Duration duration, String tenantId) {
    WorkCalendar workCalendar = map.get(tenantId);

    return workCalendar.add(date, duration);
}
 
Example 32
Project: lemon   File: MockWorkCalendarConnector.java   Source Code and License 4 votes vote down vote up
public Date add(Date date, Duration duration, String tenantId) {
    duration.addTo(date);

    return date;
}
 
Example 33
Project: openjdk-jdk10   File: AbstractDateTimeDV.java   Source Code and License 4 votes vote down vote up
protected Duration getDuration(DateTimeData data) {
    return null;
}
 
Example 34
Project: openjdk-jdk10   File: DurationTest.java   Source Code and License 4 votes vote down vote up
@Test
public void checkDurationGetTimeInMillis() {
    Duration duration86 = datatypeFactory.newDuration("PT1M1S");
    Calendar calendar86 = Calendar.getInstance();
    assertEquals(duration86.getTimeInMillis(calendar86), 61000);
}
 
Example 35
Project: lams   File: DurationConverter.java   Source Code and License 4 votes vote down vote up
@Override
public boolean canConvert(final Class<?> c) {
    return factory != null && Duration.class.isAssignableFrom(c);
}
 
Example 36
Project: openjdk-jdk10   File: DatatypeFactoryImpl.java   Source Code and License 4 votes vote down vote up
@Override
public Duration newDuration(String lexicalRepresentation) {
    return null;
}
 
Example 37
Project: openjdk-jdk10   File: DatatypeFactoryImpl.java   Source Code and License 4 votes vote down vote up
@Override
public Duration newDuration(long durationInMilliSeconds) {
    return null;
}
 
Example 38
Project: openjdk-jdk10   File: DurationTest.java   Source Code and License 4 votes vote down vote up
@Test(dataProvider = "not-equal-duration")
public void checkDurationNotEqual(String lexRepresentation1, String lexRepresentation2) {
    Duration duration1 = datatypeFactory.newDuration(lexRepresentation1);
    Duration duration2 = datatypeFactory.newDuration(lexRepresentation2);
    Assert.assertNotEquals(duration1, duration2);
}
 
Example 39
Project: openjdk-jdk10   File: DatatypeFactoryImpl.java   Source Code and License 4 votes vote down vote up
/**
    * <p>Obtain a new instance of a <code>Duration</code>
    * specifying the <code>Duration</code> as isPositive, years, months, days, hours, minutes, seconds.</p>
    *
* <p>The XML Schema specification states that values can be of an arbitrary size.
* Implementations may chose not to or be incapable of supporting arbitrarily large and/or small values.
* An {@link UnsupportedOperationException} will be thrown with a message indicating implementation limits
* if implementation capacities are exceeded.</p>
*
    * @param isPositive Set to <code>false</code> to create a negative duration. When the length
    *   of the duration is zero, this parameter will be ignored.
    * @param years of this <code>Duration</code>
    * @param months of this <code>Duration</code>
    * @param days of this <code>Duration</code>
    * @param hours of this <code>Duration</code>
    * @param minutes of this <code>Duration</code>
    * @param seconds of this <code>Duration</code>
    *
    * @return New <code>Duration</code> created from the specified values.
    *
    * @throws IllegalArgumentException If values are not a valid representation of a <code>Duration</code>.
    * @throws UnsupportedOperationException If implementation cannot support requested values.
    * @throws NullPointerException If any values are <code>null</code>.
    *
    * @see #newDuration(boolean isPositive, BigInteger years, BigInteger months, BigInteger days,
    *   BigInteger hours, BigInteger minutes, BigDecimal seconds)
    */
   public Duration newDuration(
           final boolean isPositive,
           final BigInteger years,
           final BigInteger months,
           final BigInteger days,
           final BigInteger hours,
           final BigInteger minutes,
           final BigDecimal seconds) {

           return new DurationImpl(
                           isPositive,
                           years,
                           months,
                           days,
                           hours,
                           minutes,
                           seconds
                   );
           }
 
Example 40
Project: openjdk-jdk10   File: DurationTest.java   Source Code and License 4 votes vote down vote up
@Test(expectedExceptions = NullPointerException.class)
public void checkDurationGetTimeInMillisNeg() {
    Duration duration87 = datatypeFactory.newDuration("PT1M1S");
    Calendar calendar87 = null;
    duration87.getTimeInMillis(calendar87);
}