Java Code Examples for java.time.LocalDate#atStartOfDay()

The following examples show how to use java.time.LocalDate#atStartOfDay() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LeaveServiceImpl.java    From axelor-open-suite with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Compute the duration of a given leave request but restricted inside a period.
 *
 * @param leave
 * @param fromDate the first date of the period
 * @param toDate the last date of the period
 * @return the computed duration in days
 * @throws AxelorException
 */
public BigDecimal computeDuration(LeaveRequest leave, LocalDate fromDate, LocalDate toDate)
    throws AxelorException {
  LocalDateTime leaveFromDate = leave.getFromDateT();
  LocalDateTime leaveToDate = leave.getToDateT();

  int startOn = leave.getStartOnSelect();
  int endOn = leave.getEndOnSelect();

  LocalDateTime from = leaveFromDate;
  LocalDateTime to = leaveToDate;
  // if the leave starts before the beginning of the period,
  // we use the beginning date of the period.
  if (leaveFromDate.toLocalDate().isBefore(fromDate)) {
    from = fromDate.atStartOfDay();
    startOn = LeaveRequestRepository.SELECT_MORNING;
  }
  // if the leave ends before the end of the period,
  // we use the last date of the period.
  if (leaveToDate.toLocalDate().isAfter(toDate)) {
    to = toDate.atStartOfDay();
    endOn = LeaveRequestRepository.SELECT_AFTERNOON;
  }

  return computeDuration(leave, from, to, startOn, endOn);
}
 
Example 2
Source File: MantaroBot.java    From MantaroBot with GNU General Public License v3.0 6 votes vote down vote up
public void startCheckingBirthdays() {
    ScheduledExecutorService executorService = Executors.newScheduledThreadPool(2, new ThreadFactoryBuilder().setNameFormat("Mantaro-BirthdayExecutor Thread-%d").build());
    Metrics.THREAD_POOL_COLLECTOR.add("birthday-tracker", executorService);

    //How much until tomorrow? That's the initial delay, then run it once a day.
    ZoneId z = ZoneId.of("America/Chicago");
    ZonedDateTime now = ZonedDateTime.now(z);
    LocalDate tomorrow = now.toLocalDate().plusDays(1);
    ZonedDateTime tomorrowStart = tomorrow.atStartOfDay(z);
    Duration duration = Duration.between(now, tomorrowStart);
    long millisecondsUntilTomorrow = duration.toMillis();

    //Start the birthday task on all shards.
    //This is because running them in parallel is way better than running it once for all shards.
    //It actually cut off the time from 50 minutes to 20 seconds.
    for (Shard shard : core.getShards()) {
        log.debug("Started birthday task for shard {}, scheduled to run in {} ms more", shard.getId(), millisecondsUntilTomorrow);

        executorService.scheduleWithFixedDelay(() -> BirthdayTask.handle(shard.getId()),
                millisecondsUntilTomorrow, TimeUnit.DAYS.toMillis(1), TimeUnit.MILLISECONDS);
    }

    //Start the birthday cacher.
    executorService.scheduleWithFixedDelay(birthdayCacher::cache, 22, 23, TimeUnit.HOURS);
}
 
Example 3
Source File: FormatUtils.java    From TAcharting with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Extracts the OHLC org.sjwimmer.tacharting.data from a string array into a Bar object
 * @param headerMap the header maps that maps indices colorOf the <tt>line</tt> to the {@link Parameter.Columns columns}
 * @param formatPattern the {@link DateTimeFormatter dateTimeFormatter}
 * @param line the string array with corresponding entries for the Bar
 * @return a {@link Bar Bar} object with the ohlc org.sjwimmer.tacharting.data
 */
public static Bar extractOHLCData(Map<Parameter.Columns, Integer> headerMap, DateTimeFormatter formatPattern, String[] line,boolean twoDateColumns){
    ZonedDateTime date;
    if(twoDateColumns){
        date = ZonedDateTime.parse(line[headerMap.get(Parameter.Columns.DATE)]
                +" "+line[headerMap.get(Parameter.Columns.DATE2)]+" PST", formatPattern);
    } else {
        //TODO: its a workaround, because some formats do not allow directly convert to ZonedDateTime because of missing ZoneId...
        LocalDate localDate = LocalDate.parse(line[headerMap.get(Parameter.Columns.DATE)],formatPattern);
        ZonedDateTime zonedDateTime = localDate.atStartOfDay(ZoneId.systemDefault());
        date = zonedDateTime;
    }
    double open = Double.parseDouble(line[headerMap.get(Parameter.Columns.OPEN)]);
    double high = Double.parseDouble(line[headerMap.get(Parameter.Columns.HIGH)]);
    double low = Double.parseDouble(line[headerMap.get(Parameter.Columns.LOW)]);
    double close = Double.parseDouble(line[headerMap.get(Parameter.Columns.CLOSE)]);
    double volume = Double.NaN;
    if(headerMap.get(Parameter.Columns.VOLUME) != null){
        volume = Double.parseDouble(line[headerMap.get(Parameter.Columns.VOLUME)]);
    }
    return new BaseBar(Duration.ZERO, date, open, high, low, close, volume, 0, 0, Parameter.numFunction);
}
 
Example 4
Source File: FromTemporalConverter.java    From auto-subtitle-tool with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Object convert(MappingContext<Temporal, Object> mappingContext) {
    LocalDate source = (LocalDate) mappingContext.getSource();
    Class<?> destinationType = mappingContext.getDestinationType();
    if (destinationType.equals(String.class))
        return DateTimeFormatter.ofPattern(config.getDatePattern())
                .format(source);

    LocalDateTime localDateTime = source.atStartOfDay();
    return convertLocalDateTime(localDateTime, mappingContext);
}
 
Example 5
Source File: LocalDateJavaDescriptor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <X> X unwrap(LocalDate value, Class<X> type, WrapperOptions options) {
	if ( value == null ) {
		return null;
	}

	if ( LocalDate.class.isAssignableFrom( type ) ) {
		return (X) value;
	}

	if ( java.sql.Date.class.isAssignableFrom( type ) ) {
		return (X) java.sql.Date.valueOf( value );
	}

	final LocalDateTime localDateTime = value.atStartOfDay();

	if ( Timestamp.class.isAssignableFrom( type ) ) {
		return (X) Timestamp.valueOf( localDateTime );
	}

	final ZonedDateTime zonedDateTime = localDateTime.atZone( ZoneId.systemDefault() );

	if ( Calendar.class.isAssignableFrom( type ) ) {
		return (X) GregorianCalendar.from( zonedDateTime );
	}

	final Instant instant = zonedDateTime.toInstant();

	if ( Date.class.equals( type ) ) {
		return (X) Date.from( instant );
	}

	if ( Long.class.isAssignableFrom( type ) ) {
		return (X) Long.valueOf( instant.toEpochMilli() );
	}

	throw unknownUnwrap( type );
}
 
Example 6
Source File: HUEditorRowAttributes.java    From metasfresh-webui-api-legacy with GNU General Public License v3.0 5 votes vote down vote up
private final Object convertFromJson(final I_M_Attribute attribute, final Object jsonValue)
{
	if (jsonValue == null)
	{
		return null;
	}

	final String attributeValueType = attributesStorage.getAttributeValueType(attribute);
	if (X_M_Attribute.ATTRIBUTEVALUETYPE_Date.equals(attributeValueType))
	{
		final LocalDate localDate = DateTimeConverters.fromObjectToLocalDate(jsonValue.toString());
		if (localDate == null)
		{
			return null;
		}

		// convert the LocalDate to ZonedDateTime using session's time zone,
		// because later on the date is converted to Timestamp using system's default time zone.
		// And we want to have a valid date for session's timezone.
		final ZoneId zoneId = UserSession.getTimeZoneOrSystemDefault();
		return localDate.atStartOfDay(zoneId);
	}
	else
	{
		return jsonValue;
	}
}
 
Example 7
Source File: DynamoDbBeanExample.java    From aws-doc-sdk-examples with Apache License 2.0 5 votes vote down vote up
public static void putRecord(DynamoDbEnhancedClient enhancedClient) {

        try {
            //Create a DynamoDbTable object
            DynamoDbTable<Customer> custTable = enhancedClient.table("Customer", TableSchema.fromBean(Customer.class));

            //Create am Instat
            LocalDate localDate = LocalDate.parse("2020-04-07");
            LocalDateTime localDateTime = localDate.atStartOfDay();
            Instant instant = localDateTime.toInstant(ZoneOffset.UTC);

            //Populate the Table
            Customer custRecord = new Customer();
            custRecord.setCustName("Susan Blue");
            custRecord.setId("id103");
            custRecord.setEmail("[email protected]");
            custRecord.setRegistrationDate(instant) ;

            //Put the customer data into a DynamoDB table
            custTable.putItem(custRecord);

        } catch (DynamoDbException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
        System.out.println("done");
    }
 
Example 8
Source File: IborCapletFloorletSabrRateVolatilityDataSet.java    From Strata with Apache License 2.0 5 votes vote down vote up
/**
 * Obtains {@code SabrParametersIborCapletFloorletVolatilities} with constant SABR parameters for specified valuation date.
 * 
 * @param valuationDate  the valuation date
 * @param index  the index
 * @return the volatility provider
 */
public static SabrParametersIborCapletFloorletVolatilities getVolatilitiesFlatParameters(
    LocalDate valuationDate,
    IborIndex index) {

  ZonedDateTime dateTime = valuationDate.atStartOfDay(ZoneOffset.UTC);
  return SabrParametersIborCapletFloorletVolatilities.of(NAME, index, dateTime, SABR_PARAM_FLAT);
}
 
Example 9
Source File: AbstractCityObject.java    From citygml4j with Apache License 2.0 4 votes vote down vote up
public void setCreationDate(LocalDate creationDate) {
	this.creationDate = creationDate.atStartOfDay(ZoneId.systemDefault());
}
 
Example 10
Source File: TCKLocalDate.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
@Test(expectedExceptions=NullPointerException.class)
public void test_atStartOfDay_ZoneId_null() {
    LocalDate t = LocalDate.of(2008, 6, 30);
    t.atStartOfDay((ZoneId) null);
}
 
Example 11
Source File: UseZonedDateTime.java    From tutorials with MIT License 4 votes vote down vote up
ZonedDateTime getStartOfDayShorthand(LocalDate localDate, ZoneId zone) {
    ZonedDateTime startOfDay = localDate.atStartOfDay(zone);
    return startOfDay;
}
 
Example 12
Source File: TCKLocalDate.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
@Test(expectedExceptions=NullPointerException.class)
public void test_atStartOfDay_ZoneId_null() {
    LocalDate t = LocalDate.of(2008, 6, 30);
    t.atStartOfDay((ZoneId) null);
}
 
Example 13
Source File: TCKLocalDate.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
@Test(expectedExceptions=NullPointerException.class)
public void test_atStartOfDay_ZoneId_null() {
    LocalDate t = LocalDate.of(2008, 6, 30);
    t.atStartOfDay((ZoneId) null);
}
 
Example 14
Source File: AbstractIdModelAdapter.java    From elexis-3-core with Eclipse Public License 1.0 4 votes vote down vote up
protected Date toDate(LocalDate localDate){
	ZonedDateTime atZone = localDate.atStartOfDay(ZoneId.systemDefault());
	return Date.from(atZone.toInstant());
}
 
Example 15
Source File: TCKLocalDate.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
@Test(expectedExceptions=NullPointerException.class)
public void test_atStartOfDay_ZoneId_null() {
    LocalDate t = LocalDate.of(2008, 6, 30);
    t.atStartOfDay((ZoneId) null);
}
 
Example 16
Source File: TCKLocalDate.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
@Test(expectedExceptions=NullPointerException.class)
public void test_atStartOfDay_ZoneId_null() {
    LocalDate t = LocalDate.of(2008, 6, 30);
    t.atStartOfDay((ZoneId) null);
}
 
Example 17
Source File: OrcTester.java    From presto with Apache License 2.0 4 votes vote down vote up
private static Object preprocessWriteValueHive(Type type, Object value)
{
    if (value == null) {
        return null;
    }

    if (type.equals(BOOLEAN)) {
        return value;
    }
    if (type.equals(TINYINT)) {
        return ((Number) value).byteValue();
    }
    if (type.equals(SMALLINT)) {
        return ((Number) value).shortValue();
    }
    if (type.equals(INTEGER)) {
        return ((Number) value).intValue();
    }
    if (type.equals(BIGINT)) {
        return ((Number) value).longValue();
    }
    if (type.equals(REAL)) {
        return ((Number) value).floatValue();
    }
    if (type.equals(DOUBLE)) {
        return ((Number) value).doubleValue();
    }
    if (type instanceof VarcharType) {
        return value;
    }
    if (type instanceof CharType) {
        return new HiveChar((String) value, ((CharType) type).getLength());
    }
    if (type.equals(VARBINARY)) {
        return ((SqlVarbinary) value).getBytes();
    }
    if (type.equals(DATE)) {
        int days = ((SqlDate) value).getDays();
        LocalDate localDate = LocalDate.ofEpochDay(days);
        ZonedDateTime zonedDateTime = localDate.atStartOfDay(ZoneId.systemDefault());

        long millis = SECONDS.toMillis(zonedDateTime.toEpochSecond());
        Date date = new Date(0);
        // millis must be set separately to avoid masking
        date.setTime(millis);
        return date;
    }
    if (type.equals(TIMESTAMP)) {
        long millisUtc = ((SqlTimestamp) value).getMillisUtc();
        return new Timestamp(millisUtc);
    }
    if (type instanceof DecimalType) {
        return HiveDecimal.create(((SqlDecimal) value).toBigDecimal());
    }
    if (type instanceof ArrayType) {
        Type elementType = type.getTypeParameters().get(0);
        return ((List<?>) value).stream()
                .map(element -> preprocessWriteValueHive(elementType, element))
                .collect(toList());
    }
    if (type instanceof MapType) {
        Type keyType = type.getTypeParameters().get(0);
        Type valueType = type.getTypeParameters().get(1);
        Map<Object, Object> newMap = new HashMap<>();
        for (Entry<?, ?> entry : ((Map<?, ?>) value).entrySet()) {
            newMap.put(preprocessWriteValueHive(keyType, entry.getKey()), preprocessWriteValueHive(valueType, entry.getValue()));
        }
        return newMap;
    }
    if (type instanceof RowType) {
        List<?> fieldValues = (List<?>) value;
        List<Type> fieldTypes = type.getTypeParameters();
        List<Object> newStruct = new ArrayList<>();
        for (int fieldId = 0; fieldId < fieldValues.size(); fieldId++) {
            newStruct.add(preprocessWriteValueHive(fieldTypes.get(fieldId), fieldValues.get(fieldId)));
        }
        return newStruct;
    }
    throw new IllegalArgumentException("unsupported type: " + type);
}
 
Example 18
Source File: SwaptionSabrRateVolatilityDataSet.java    From Strata with Apache License 2.0 2 votes vote down vote up
/**
 * Obtains {@code SABRVolatilitySwaptionProvider} for specified valuation date.
 * 
 * @param valuationDate  the valuation date
 * @param shift  nonzero shift if true, zero shift otherwise
 * @return the volatility provider
 */
public static SabrParametersSwaptionVolatilities getVolatilitiesUsd(LocalDate valuationDate, boolean shift) {
  ZonedDateTime dateTime = valuationDate.atStartOfDay(ZoneOffset.UTC);
  return shift ? SabrParametersSwaptionVolatilities.of(NAME, SWAP_CONVENTION_USD, dateTime, SABR_PARAM_SHIFT_USD)
      : SabrParametersSwaptionVolatilities.of(NAME, SWAP_CONVENTION_USD, dateTime, SABR_PARAM_USD);
}
 
Example 19
Source File: AbstractFindingsAccessor.java    From elexis-3-core with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Method to convert form {@link LocalDateTime} to {@link Date}
 * 
 * @param localDateTime
 * @return
 */
protected Date getDate(LocalDate localDate){
	ZonedDateTime zdt = localDate.atStartOfDay(ZoneId.systemDefault());
	return Date.from(zdt.toInstant());
}
 
Example 20
Source File: IFinding.java    From elexis-3-core with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Default method to convert form {@link LocalDateTime} to {@link Date}
 * 
 * @param localDateTime
 * @return
 */
default Date getDate(LocalDate localDate){
	ZonedDateTime zdt = localDate.atStartOfDay(ZoneId.systemDefault());
	return Date.from(zdt.toInstant());
}