Java Code Examples for java.util.Date.from()

The following are Jave code examples for showing how to use from() of the java.util.Date class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: git-rekt   File: BrowseRoomsScreenController.java   View Source Code Vote up 6 votes
/**
 * Searches the database for rooms that are available in the given date range.
 */
@FXML
private void onFindAvailableRoomsButtonClicked() {
    // The new date api is great. Converting back and forth, not so much.
    LocalDate checkInDateTemp = checkInDatePicker.getValue();
    LocalDate checkOutDateTemp = checkOutDatePicker.getValue();
    Instant temp1 = Instant.from(checkInDateTemp.atStartOfDay(ZoneId.systemDefault()));
    Instant temp2 = Instant.from(checkOutDateTemp.atStartOfDay(ZoneId.systemDefault()));
    Date checkInDate = Date.from(temp1);
    Date checkOutDate = Date.from(temp2);

    // Clear any existing results
    roomSearchResults.clear();
    selectedRooms.clear();

    // Get the new results
    BookingService bookingService = new BookingService();
    roomSearchResults.addAll(bookingService.getRoomTypesAvailable(checkInDate, checkOutDate));
}
 
Example 2
Project: IKB4Stream   File: TwitterMock.java   View Source Code Vote up 6 votes
/**
 * Parse an object node in order to create an {@link Event} object
 *
 * @param objectNode object node to convert to {@link Event}
 * @return {@link Event} converted format
 * @see TwitterMock#SOURCE
 */
@Override
public Event getEventFromJson(ObjectNode objectNode) {
    Date startDate = Date.from(Instant.ofEpochMilli(objectNode.findValue("timestamp_ms").asLong()));
    Date endDate = Date.from(Instant.now());
    JsonNode jsonNode = objectNode.findValue("place");
    JsonNode jsonCoordinates = jsonNode.findValue("coordinates");
    String description = objectNode.findValue("text").toString();
    LatLong latLong = jsonToLatLong(jsonCoordinates);
    try {
        return new Event(latLong, startDate, endDate, description, SOURCE);
    } catch (IllegalArgumentException | NullPointerException err) {
        LOGGER.error(err.getMessage());
        return null;
    }
}
 
Example 3
Project: osoon   File: User.java   View Source Code Vote up 5 votes
public static User of(String email, String name) {
	User user = new User();
	user.email = email;
	user.name = name;
	user.nickname = name;
	user.password = email;

	ZonedDateTime utc = ZonedDateTime.now(ZoneOffset.UTC);
	user.joinedAt = Date.from(utc.toInstant());

	return user;
}
 
Example 4
Project: Spring-web-shop-project   File: CookiesDAO.java   View Source Code Vote up 5 votes
public static Date getEndCookieDate(int days) {
    Date date = new Date();
    LocalDateTime localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
    localDate = localDate.plusDays(days);
    Date cookieEndDate = Date.from(localDate.atZone(ZoneId.systemDefault()).toInstant());
    return cookieEndDate;
}
 
Example 5
Project: GoupilBot   File: DateTimeLib.java   View Source Code Vote up 5 votes
/**
 * Cette méthode transforme un objet LocalDate (Java 8) en un objet Date.
 * L'objet LocalDate ne possédant pas d'heure, on lui donne minuit et la zone horaire du système.
 *
 * @param localDate l'objet LocalDate à transformer en Date
 * @return l'objet Date correspondant à l'objet LocalDate
 */
public static Date localDateToDate(LocalDate localDate) {
  if (localDate != null) {
    return Date.from(Instant.from(localDate.atStartOfDay(ZoneId.systemDefault())));
  } else {
    return null;
  }
}
 
Example 6
Project: dracoon-dropzone   File: Util.java   View Source Code Vote up 5 votes
/**
 * Adds the given number of days to today and returns the new date
 * 
 * @param days
 * @return
 */
public static Date getDaysFromNow(int days) {
	LocalDate localDate = LocalDate.now().plus(days, ChronoUnit.DAYS);
	Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
	return date;

}
 
Example 7
Project: holon-vaadin7   File: DateToLocalDateConverter.java   View Source Code Vote up 5 votes
@Override
public Date convertToPresentation(LocalDate value, Class<? extends Date> targetType, Locale locale)
		throws com.vaadin.data.util.converter.Converter.ConversionException {
	if (value != null) {
		return Date.from(value.atStartOfDay(getTimeZone()).toInstant());
	}
	return null;
}
 
Example 8
Project: aws-sdk-java-v2   File: StepFunctionBuilderTest.java   View Source Code Vote up 5 votes
@Test
public void choiceStateWithAllPrimitiveConditions() {
    final Date date = Date.from(ZonedDateTime.parse("2016-03-14T01:59:00.000Z").toInstant());
    final StateMachine stateMachine = stateMachine()
            .startAt("InitialState")
            .state("InitialState", choiceState()
                    .defaultStateName("DefaultState")
                    .choice(choice().transition(next("NextState"))
                                    .condition(and(
                                            eq("$.string", "value"),
                                            gt("$.string", "value"),
                                            gte("$.string", "value"),
                                            lt("$.string", "value"),
                                            lte("$.string", "value"),
                                            eq("$.integral", 42),
                                            gt("$.integral", 42),
                                            gte("$.integral", 42),
                                            lt("$.integral", 42),
                                            lte("$.integral", 42),
                                            eq("$.double", 9000.1),
                                            gt("$.double", 9000.1),
                                            gte("$.double", 9000.1),
                                            lt("$.double", 9000.1),
                                            lte("$.double", 9000.1),
                                            eq("$.timestamp", date),
                                            gt("$.timestamp", date),
                                            gte("$.timestamp", date),
                                            lt("$.timestamp", date),
                                            lte("$.timestamp", date),
                                            eq("$.boolean", true),
                                            eq("$.boolean", false)
                                                  ))))
            .state("NextState", succeedState())
            .state("DefaultState", succeedState())
            .build();

    assertStateMachine(stateMachine, "ChoiceStateWithAllPrimitiveCondition.json");
}
 
Example 9
Project: NekoooGuilds   File: NekoooGuilds.java   View Source Code Vote up 4 votes
private void setupFS() throws IOException {
    log.config("Setting up filesystem...");

    Collection<File> directories = new ArrayList<File>();

    File reportsfolder = new File("ng-reports");

    directories.add(bridge.getNGFolder());
    directories.add(new File(bridge.getNGFolder(), "config"));
    directories.add(new File(bridge.getNGFolder(), "data"));
    directories.add(new File(bridge.getNGFolder(), "commands"));
    directories.add(new File(bridge.getNGFolder(), "scripts"));
    directories.add(reportsfolder);

    for (File f : directories) {
        if (f == null) continue;
        if (!f.exists()) {
            f.mkdir();
        } else {
            if (!f.isDirectory()) {
                if (f.delete()) {
                    f.mkdir();
                } else {
                    reportError(new IOException("Cannot fix " + f.getName() + "."));
                }
            }
        }
    }

    if (!System.getProperty("nekoooguilds.dontcleanreports", "false").equalsIgnoreCase("true")) {
        log.config("Cleaning up old reports...");
        LocalDate today = LocalDate.now();
        LocalDate eailer = today.minusDays(14);

        Date threshold = Date.from(eailer.atStartOfDay(ZoneId.systemDefault()).toInstant());
        AgeFileFilter filter = new AgeFileFilter(threshold);

        File[] remove = FileFilterUtils.filter(filter, reportsfolder);

        for (File file : remove) {
            if (file.delete()) log.config("Deleted " + file.getName());
        }
    } else {
        log.info("Report cleanup disabled with JVM/PropertyLoader option.");
    }
}
 
Example 10
Project: users-service   File: DateServiceImpl.java   View Source Code Vote up 4 votes
@Override
public Date now() {
    return Date.from(instantNow());
}
 
Example 11
Project: trade-insights   File: TradeRecommendationsEngine.java   View Source Code Vote up 4 votes
private Date determineTradeWindowStartDate(){
 LocalDateTime today = LocalDateTime.now();
 return Date.from(today.atZone(ZoneId.systemDefault()).toInstant());
 
}
 
Example 12
Project: OnlineShop   File: OrderController.java   View Source Code Vote up 4 votes
@RequestMapping(value = "get", produces = "application/json", method = RequestMethod.GET)
public OrderObject doGet(){
     return new OrderObject(new HashMap<Long, Long>(), Date.from(Instant.now()), "ceva");
}
 
Example 13
Project: simple-openid-provider   File: DefaultTokenService.java   View Source Code Vote up 4 votes
@Override
public JWT createIdToken(IdTokenRequest idTokenRequest) {
	Instant now = Instant.now();
	Subject subject = idTokenRequest.getSubject();
	OIDCClientInformation client = idTokenRequest.getClient();
	ClientID clientId = client.getID();
	JWSAlgorithm algorithm = client.getOIDCMetadata().getIDTokenJWSAlg();
	UserInfo userInfo = this.claimSource.load(subject, resolveClaims(idTokenRequest));
	List<Audience> audience = Audience.create(clientId.getValue());
	Date expirationTime = Date.from(now.plus(this.idTokenLifetime));
	Date issueTime = Date.from(now);

	IDTokenClaimsSet claimsSet = new IDTokenClaimsSet(this.issuer, userInfo.getSubject(), audience, expirationTime,
			issueTime);
	claimsSet.setAuthenticationTime(Date.from(idTokenRequest.getAuthenticationTime()));
	claimsSet.setNonce(idTokenRequest.getNonce());
	claimsSet.setACR(idTokenRequest.getAcr());
	claimsSet.setAMR(Collections.singletonList(idTokenRequest.getAmr()));
	claimsSet.setAuthorizedParty(new AuthorizedParty(clientId.getValue()));
	claimsSet.putAll(userInfo);

	if (this.frontChannelLogoutEnabled) {
		SessionID sessionId = idTokenRequest.getSessionId();
		claimsSet.setSessionID(sessionId);
	}

	AccessToken accessToken = idTokenRequest.getAccessToken();

	if (accessToken != null) {
		AccessTokenHash accessTokenHash = AccessTokenHash.compute(accessToken, algorithm);
		claimsSet.setAccessTokenHash(accessTokenHash);
	}

	AuthorizationCode code = idTokenRequest.getCode();

	if (code != null) {
		CodeHash codeHash = CodeHash.compute(code, algorithm);
		claimsSet.setCodeHash(codeHash);
	}

	try {
		JWTAssertionDetails details = JWTAssertionDetails.parse(claimsSet.toJWTClaimsSet());

		if (JWSAlgorithm.Family.HMAC_SHA.contains(algorithm)) {
			Secret secret = client.getSecret();

			return JWTAssertionFactory.create(details, algorithm, secret);
		}
		else if (JWSAlgorithm.Family.RSA.contains(algorithm)) {
			RSAKey rsaKey = (RSAKey) resolveJwk(algorithm);

			return JWTAssertionFactory.create(details, algorithm, rsaKey.toRSAPrivateKey(), rsaKey.getKeyID(),
					jcaProvider);
		}
		else if (JWSAlgorithm.Family.EC.contains(algorithm)) {
			ECKey ecKey = (ECKey) resolveJwk(algorithm);

			return JWTAssertionFactory.create(details, algorithm, ecKey.toECPrivateKey(), ecKey.getKeyID(),
					jcaProvider);
		}

		throw new KeyException("Unsupported algorithm: " + algorithm);
	}
	catch (ParseException | JOSEException e) {
		throw new RuntimeException(e);
	}
}
 
Example 14
Project: tifoon   File: TimeHelper.java   View Source Code Vote up 4 votes
public static Date toDate(final long _timestamp) {
    return Date.from(Instant.ofEpochMilli(_timestamp));
}
 
Example 15
Project: flow-platform   File: DateUtil.java   View Source Code Vote up 4 votes
public static Date toDate(ZonedDateTime zonedDateTime) {
    return Date.from(zonedDateTime.toInstant());
}
 
Example 16
Project: CalendarFX   File: ICalCalendar.java   View Source Code Vote up 4 votes
private synchronized void load(int year) {
    if (alreadyLoadedYears.contains(year)) {
        return;
    }

    alreadyLoadedYears.add(year);

    ZonedDateTime st = ZonedDateTime.of(LocalDate.now().with(TemporalAdjusters.firstDayOfYear()), LocalTime.MIN, ZoneId.systemDefault());
    ZonedDateTime et = ZonedDateTime.of(LocalDate.now().with(TemporalAdjusters.lastDayOfYear()), LocalTime.MAX, ZoneId.systemDefault());

    try {
        startBatchUpdates();

        /*
         * Convert start and end times from new java.time API to old API and then to ical API :-)
         */
        Period period = new Period(
                new DateTime(Date.from(st.toInstant())),
                new DateTime(Date.from(et.toInstant())));

        Rule[] rules = new Rule[]{new PeriodRule(period)};
        Filter filter = new Filter(rules, Filter.MATCH_ANY);

        @SuppressWarnings("unchecked")
        Collection<VEvent> events = filter.filter(calendar.getComponents(Component.VEVENT));

        for (VEvent evt : events) {

            if (loadedEventIds.contains(evt.getUid())) {
                continue;
            }

            loadedEventIds.add(evt.getUid());

            ICalCalendarEntry entry = new ICalCalendarEntry(evt);

            ZonedDateTime entryStart = ZonedDateTime.ofInstant(evt.getStartDate().getDate().toInstant(), ZoneId.systemDefault());

            ZonedDateTime entryEnd = ZonedDateTime.ofInstant(evt
                            .getEndDate().getDate().toInstant(),
                    ZoneId.systemDefault());

            if (entryEnd.toLocalDate().isAfter(entryStart.toLocalDate())) {
                entryEnd = entryEnd.minusDays(1);
                entry.setFullDay(true);
            }

            entry.setInterval(new Interval(entryStart, entryEnd));

            final Property prop = evt.getProperty("RRULE");
            if (prop instanceof RRule) {
                RRule rrule = (RRule) prop;
                entry.setRecurrenceRule("RRULE:" + rrule.getValue());
            }

            addEntry(entry);
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        stopBatchUpdates();
    }
}
 
Example 17
Project: git-rekt   File: PlaceBookingScreenController.java   View Source Code Vote up 4 votes
@FXML
private void onFinishButtonClicked() {
    boolean validInput = validateInput();
    if(validInput) {
        // Gather the form data
        String firstName = firstNameField.getText().trim();
        String lastName = lastNameField.getText().trim();
        String email = emailField.getText().trim();
        String addressLine1 = addressLine1Field.getText().trim();
        String addressLine2 = addressLine2Field.getText().trim();
        String city = cityField.getText().trim();
        String country = countryPicker.getValue().trim();
        String postalCode = postalCodeField.getText().trim();
        String specialInstructions = specialInstructionsBox.getText().trim();

        // Mailing address shouold not include a state if the guest doesn't live in the US
        MailingAddress mailingAddress;
        if(country.equals("United States")) {
            UsState state = UsState.parse(statePicker.getValue());
            mailingAddress = new MailingAddress(
                addressLine1, addressLine2, city, postalCode, state, country
            );
        } else {
            mailingAddress = new MailingAddress(
                addressLine1, addressLine2, city, postalCode, null, country
            );
        }

        // Gather the needed data to create the booking
        BookingService bookingService = new BookingService();
        Date checkin = Date.from(
            checkInDate.atStartOfDay(ZoneId.systemDefault()).toInstant()
        );
        Date checkout = Date.from(
            checkOutDate.atStartOfDay(ZoneId.systemDefault()).toInstant()
        );
        List<Package> packagesToBook = getListOfPackagesToBook();
        List<Room> roomsToBook;
        try {
            roomsToBook = getListOfRoomsToBook(checkin, checkout);
        } catch (IllegalStateException e) {
            showNoMoreRoomsInCategoryErrorDialog();
            return;
        }
        Guest guest = findOrCreateGuest(firstName, lastName, email, mailingAddress);

        Booking booking = new Booking(
            guest, checkin, checkout, specialInstructions, packagesToBook, roomsToBook
        );

        bookingService.createBooking(booking);
        displayBookingNumberAndReturnHome();
    }
}
 
Example 18
Project: sweiproject-tg2b-1   File: TokenPurge.java   View Source Code Vote up 4 votes
/**
 * Deleting all tokens from {@link #tokenRepository}, which have been expired since now.
 */
@Scheduled(cron = "0 0 0 * * *")
public void purgeExpired() {
    final Date now = Date.from(Instant.now());
    tokenRepository.deleteAllExpiredSince(now);
}
 
Example 19
Project: happylifeplat-tcc   File: DateUtils.java   View Source Code Vote up 4 votes
public static Date getDateYYYY() throws  ParseException{
    LocalDateTime localDateTime = parseLocalDateTime(getCurrentDateTime());
    ZoneId zone = ZoneId.systemDefault();
    Instant instant = localDateTime.atZone(zone).toInstant();
    return Date.from(instant);
}
 
Example 20
Project: mot-public-api   File: TradeReadServiceTest.java   View Source Code Vote up 2 votes
/**
 * Converts a LocalDateTime to a Date in the system's default time zone.
 *
 * @param ldt LocalDateTime to convert
 * @return Date caused by interpreting the LocalDateTime in the system default time zone
 */
private static Date localDateTimeToDate(LocalDateTime ldt) {

    return Date.from(ldt.atZone(ZoneId.systemDefault()).toInstant());
}