Java Code Examples for java.time.ZoneId

The following are top voted examples for showing how to use java.time.ZoneId. 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: jdk8u-jdk   File: TestZoneId.java   Source Code and License 6 votes vote down vote up
public void test_NewYork_getOffsetInfo_overlap() {
    ZoneId test = ZoneId.of("America/New_York");
    final LocalDateTime dateTime = LocalDateTime.of(2008, 11, 2, 1, 0, 0, 0);
    ZoneOffsetTransition trans = checkOffset(test.getRules(), dateTime, ZoneOffset.ofHours(-4), OVERLAP);
    assertEquals(trans.getOffsetBefore(), ZoneOffset.ofHours(-4));
    assertEquals(trans.getOffsetAfter(), ZoneOffset.ofHours(-5));
    assertEquals(trans.getInstant(), createInstant(2008, 11, 2, 2, 0, 0, 0, ZoneOffset.ofHours(-4)));
    assertEquals(trans.isValidOffset(ZoneOffset.ofHours(-1)), false);
    assertEquals(trans.isValidOffset(ZoneOffset.ofHours(-5)), true);
    assertEquals(trans.isValidOffset(ZoneOffset.ofHours(-4)), true);
    assertEquals(trans.isValidOffset(ZoneOffset.ofHours(2)), false);
    assertEquals(trans.toString(), "Transition[Overlap at 2008-11-02T02:00-04:00 to -05:00]");

    assertFalse(trans.equals(null));
    assertFalse(trans.equals(ZoneOffset.ofHours(-4)));
    assertTrue(trans.equals(trans));

    final ZoneOffsetTransition otherTrans = test.getRules().getTransition(dateTime);
    assertTrue(trans.equals(otherTrans));

    assertEquals(trans.hashCode(), otherTrans.hashCode());
}
 
Example 2
Project: device-opcua-java   File: ScheduleContext.java   Source Code and License 6 votes vote down vote up
private ZonedDateTime parseTime(String time) {
  // TODO : may support more than one format at some point
  DateTimeFormatter dtf =
      DateTimeFormatter.ofPattern(Schedule.DATETIME_FORMATS[0]).withZone(ZoneId.systemDefault());
  ZonedDateTime zdt = null;

  try {
    zdt = ZonedDateTime.parse(time, dtf);
  } catch (DateTimeParseException e) {
    logger.debug("parseTime() failed to parse '" + time + "'");
    // throw an exception
    // mark as complete (via max iterations?)
  }

  return zdt;
}
 
Example 3
Project: morpheus-core   File: Formats.java   Source Code and License 6 votes vote down vote up
/**
 * Registers the default parsers for these formats
 * NOTE THAT THE ORDER IN WHICH THESE ARE REGISTERED MATTERS SOMEWHAT (MORE SPECIFIC TO LESS SPECIFIC)
 */
private void registerParsers() {
    this.setParser(boolean.class, Parser.ofBoolean().withNullChecker(nullCheck));
    this.setParser(Boolean.class, Parser.ofBoolean().withNullChecker(nullCheck));
    this.setParser(int.class, Parser.ofInteger().withNullChecker(nullCheck));
    this.setParser(Integer.class, Parser.ofInteger().withNullChecker(nullCheck));
    this.setParser(long.class, Parser.ofLong().withNullChecker(nullCheck));
    this.setParser(Long.class, Parser.ofLong().withNullChecker(nullCheck));
    this.setParser(double.class, Parser.ofDouble("0.0000####;-0.0000####", 1).withNullChecker(nullCheck));
    this.setParser(Double.class, Parser.ofDouble("0.0000####;-0.0000####", 1).withNullChecker(nullCheck));
    this.setParser(BigDecimal.class, Parser.ofBigDecimal().withNullChecker(nullCheck));
    this.setParser(LocalDate.class, Parser.ofLocalDate(DateTimeFormatter.ISO_LOCAL_DATE).withNullChecker(nullCheck));
    this.setParser(LocalTime.class, Parser.ofLocalTime(DateTimeFormatter.ISO_LOCAL_TIME).withNullChecker(nullCheck));
    this.setParser(LocalDateTime.class, Parser.ofLocalDateTime(DateTimeFormatter.ISO_LOCAL_DATE_TIME).withNullChecker(nullCheck));
    this.setParser(ZonedDateTime.class, Parser.ofZonedDateTime(DateTimeFormatter.ISO_ZONED_DATE_TIME).withNullChecker(nullCheck));
    this.setParser(Period.class, Parser.ofPeriod().withNullChecker(nullCheck));
    this.setParser(ZoneId.class, Parser.ofZoneId().withNullChecker(nullCheck));
    this.setParser(Month.class, Parser.ofEnum(Month.class).withNullChecker(nullCheck));
    this.setParser(TimeZone.class, Parser.ofTimeZone().withNullChecker(nullCheck));
    this.setParser(java.util.Date.class, Parser.ofDate().withNullChecker(nullCheck));
    this.setParser(String.class, Parser.ofString().withNullChecker(nullCheck));
    this.setParser(Object.class, Parser.ofObject().withNullChecker(nullCheck));
}
 
Example 4
Project: morpheus-core   File: FormatsTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testParseNullsWithSpecificCharacter() {
    final Formats formats = new Formats();
    formats.setNullValues("null", "-");
    assertEquals(formats.getParserOrFail(boolean.class).apply("-"), Boolean.FALSE);
    assertEquals(formats.getParserOrFail(boolean.class).apply("-"), Boolean.FALSE);
    assertEquals(formats.getParserOrFail(Boolean.class).apply("-"), Boolean.FALSE);
    assertEquals(formats.getParserOrFail(Boolean.class).apply("-"), Boolean.FALSE);
    assertEquals(formats.getParserOrFail(Integer.class).apply("-"), 0);
    assertEquals(formats.getParserOrFail(int.class).apply("-"), 0);
    assertEquals(formats.getParserOrFail(Long.class).apply("-"), 0L);
    assertEquals(formats.getParserOrFail(long.class).apply("-"), 0L);
    assertEquals(formats.getParserOrFail(Double.class).apply("-"), Double.NaN);
    assertEquals(formats.getParserOrFail(double.class).apply("-"), Double.NaN);
    assertEquals(formats.getParserOrFail(String.class).apply("-"), null);
    assertEquals(formats.getParserOrFail(ZoneId.class).apply("-"), null);
    assertEquals(formats.getParserOrFail(TimeZone.class).apply("-"), null);
    assertEquals(formats.getParserOrFail(LocalDate.class).apply("-"), null);
    assertEquals(formats.getParserOrFail(LocalDateTime.class).apply("-"), null);
    assertEquals(formats.getParserOrFail(ZonedDateTime.class).apply("-"), null);
}
 
Example 5
Project: git-rekt   File: BrowseRoomsScreenController.java   Source Code and License 6 votes vote down vote up
/**
 * 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 6
Project: CalendarFX   File: DateControlSkin.java   Source Code and License 6 votes vote down vote up
protected boolean isRelevant(Entry<?> entry) {

        if (this instanceof LoadDataSettingsProvider) {
            C dateControl = getSkinnable();

            if (!(entry instanceof DraggedEntry) && !dateControl.isCalendarVisible(entry.getCalendar())) {
                return false;
            }

            LoadDataSettingsProvider provider = (LoadDataSettingsProvider) this;

            ZoneId zoneId = getSkinnable().getZoneId();
            LocalDate loadStartDate = provider.getLoadStartDate();
            LocalDate loadEndDate = provider.getLoadEndDate();

            return entry.isShowing(loadStartDate, loadEndDate, zoneId);
        }

        return false;
    }
 
Example 7
Project: bouncr   File: SignInService.java   Source Code and License 6 votes vote down vote up
public PasswordCredentialStatus validatePasswordCredentialAttributes(User user) {
    PasswordCredentialDao passwordCredentialDao = daoProvider.getDao(PasswordCredentialDao.class);
    PasswordCredential passwordCredential = passwordCredentialDao.selectById(user.getId());

    if (passwordCredential.isInitial()) {
        return INITIAL;
    }

    if (config.getPasswordPolicy().getExpires() != null) {
        Instant createdAt = passwordCredential.getCreatedAt().toInstant(ZoneId.systemDefault().getRules().getOffset(Instant.now()));
        return (createdAt.plus(config.getPasswordPolicy().getExpires()).isBefore(config.getClock().instant())) ?
                EXPIRED : VALID;
    }

    return VALID;
}
 
Example 8
Project: ABC-List   File: DateConverterTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testIsDateInNewRange() {
    LocalDateTime localDateTimeNow = LocalDateTime.now();
    long milliesNow = localDateTimeNow.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
    boolean isDateInNewRange = DateConverter.getDefault().isDateInNewRange(milliesNow);
    assertTrue(isDateInNewRange);
    
    localDateTimeNow = LocalDateTime.now().minusDays(2).minusHours(23);
    milliesNow = localDateTimeNow.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
    isDateInNewRange = DateConverter.getDefault().isDateInNewRange(milliesNow);
    assertTrue(isDateInNewRange);
    
    localDateTimeNow = LocalDateTime.now().minusDays(4);
    milliesNow = localDateTimeNow.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
    isDateInNewRange = DateConverter.getDefault().isDateInNewRange(milliesNow);
    assertFalse(isDateInNewRange);
}
 
Example 9
Project: gdl2   File: Interpreter.java   Source Code and License 6 votes vote down vote up
private List<DataInstance> evaluateMinOrMaxFunction(List<DataInstance> dataInstances, UnaryExpression unaryExpression, boolean minFunction) {
    DataInstance found = null;
    long milliseconds = 0;
    for (DataInstance dataInstance : dataInstances) {
        Object value = evaluateExpressionItem(unaryExpression.getOperand(), dataInstance.valueListMap());
        if (value instanceof DvDateTime) {
            DvDateTime dvDateTime = (DvDateTime) value;
            long convertedDateTime = dvDateTime.getDateTime().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
            if (minFunction) {
                if (found == null || convertedDateTime < milliseconds) {
                    found = dataInstance;
                    milliseconds = convertedDateTime;
                }
            } else { // maxFunction
                if (found == null || convertedDateTime > milliseconds) {
                    found = dataInstance;
                    milliseconds = convertedDateTime;
                }
            }
        }
    }
    return found == null ? Collections.emptyList() : Collections.singletonList(found);
}
 
Example 10
Project: morpheus-core   File: RangeSplitTests.java   Source Code and License 6 votes vote down vote up
@Test(dataProvider = "directions")
public void testSplitZonedDateTimes(boolean ascending) {
    final Duration step = Duration.ofSeconds(1);
    final ZonedDateTime start = ZonedDateTime.of(2014, 1, 1, 14, 15, 20, 0, ZoneId.systemDefault());
    final ZonedDateTime end = start.plusSeconds(10000000 * (ascending ? 1 : -1));
    final Range<ZonedDateTime> range = Range.of(start, end, step);
    final List<Range<ZonedDateTime>> segments = range.split();
    Assert.assertTrue(segments.size() > 1, "There are multiple segments");
    for (int i=1; i<segments.size(); ++i) {
        final Range<ZonedDateTime> prior = segments.get(i-1);
        final Range<ZonedDateTime> next = segments.get(i);
        Assert.assertEquals(prior.end(), next.start(), "Date connect as expect");
        if (i == 1) Assert.assertEquals(prior.start(), range.start(), "First segment start matches range start");
        if (i == segments.size()-1) {
            Assert.assertEquals(next.end(), range.end(), "Last segment end matches range end");
        }
    }
}
 
Example 11
Project: jdk8u-jdk   File: TCKZoneIdPrinterParser.java   Source Code and License 6 votes vote down vote up
@Test(dataProvider="parseSuccess")
public void test_parseSuccess_prefix(String text, int expectedIndex, int expectedErrorIndex, ZoneId expected) {
    builder.appendZoneId();
    pos.setIndex(3);
    String prefixText = "XXX" + text;
    TemporalAccessor parsed = builder.toFormatter().parseUnresolved(prefixText, pos);
    assertEquals(pos.getErrorIndex(), expectedErrorIndex >= 0  ? expectedErrorIndex + 3 : expectedErrorIndex, "Incorrect error index parsing: " + prefixText);
    assertEquals(pos.getIndex(), expectedIndex + 3, "Incorrect index parsing: " + prefixText);
    if (expected != null) {
        assertEquals(parsed.query(TemporalQueries.zoneId()), expected, "Incorrect zoneId parsing: " + prefixText);
        assertEquals(parsed.query(TemporalQueries.offset()), null, "Incorrect offset parsing: " + prefixText);
        assertEquals(parsed.query(TemporalQueries.zone()), expected, "Incorrect zone parsing: " + prefixText);
    } else {
        assertEquals(parsed, null);
    }
}
 
Example 12
Project: galop   File: ResponseBuilder.java   Source Code and License 6 votes vote down vote up
private void buildDateHeader(final StringBuilder builder) {

        ZonedDateTime dateTime;

        if (this.dateTime != null) {
            dateTime = this.dateTime;
        } else {
            dateTime = ZonedDateTime.now(ZoneId.of("GMT"));
        }

        builder.append(Constants.HEADER_DATE_PREFIX);
        builder.append(Constants.SPACE);
        builder.append(DateTimeFormatter.RFC_1123_DATE_TIME.format(dateTime));
        builder.append(Constants.NEW_LINE);

    }
 
Example 13
Project: galop   File: ResponseBuilderTest.java   Source Code and License 6 votes vote down vote up
@Test
public void build_withDateTimeAndWithoutContent_returnsResponseWithDefaultContent() {

    final ZonedDateTime dateTime = ZonedDateTime.of(2017, 3, 20, 19, 9, 3, 40, ZoneId.of("GMT"));
    final ResponseBuilder httpResponse = ResponseBuilder
            .createWithStatus(StatusCode.BAD_REQUEST)
            .dateTime(dateTime);

    final Charset expectedCharset = Charset.forName("UTF-8");
    final String expectedDefaultContent = StatusCode.BAD_REQUEST.getReason();
    final byte[] expectedDefaultContentBytes = expectedDefaultContent.getBytes(expectedCharset);
    final String expectedHttpResponse = "HTTP/1.1 400 Bad Request\r\n"
            + "date: Mon, 20 Mar 2017 19:09:03 GMT\r\n"
            + "content-length: " + expectedDefaultContentBytes.length + "\r\n"
            + "content-type: text/plain; charset=UTF-8\r\n"
            + "\r\n"
            + expectedDefaultContent;
    assertEquals(expectedHttpResponse, new String(httpResponse.build(), expectedCharset));

}
 
Example 14
Project: morpheus-core   File: DenseArrayOfZonedDateTimes.java   Source Code and License 6 votes vote down vote up
@Override
public final boolean isEqualTo(int index, ZonedDateTime value) {
    if (value == null) {
        return values[index] == nullValue;
    } else {
        final long epochMills = value.toInstant().toEpochMilli();
        if (epochMills != values[index]) {
            return false;
        } else {
            final ZoneId zoneId = value.getZone();
            final short code1 = zoneIdMap1.get(zoneId);
            final short code2 = zoneIds[index];
            return code1 == code2;
        }
    }
}
 
Example 15
Project: cactoos   File: DateAsText.java   Source Code and License 5 votes vote down vote up
/**
 * Formats the milliseconds as date using the format and the locale.
 * @param milliseconds Milliseconds to format as date.
 * @param format The format to use.
 * @param locale The locale to use for the format.
 */
public DateAsText(final long milliseconds, final String format,
    final Locale locale) {
    this(
        ZonedDateTime.ofInstant(
            Instant.ofEpochMilli(milliseconds), ZoneId.of("UTC")
        ),
        DateTimeFormatter.ofPattern(format, locale)
    );
}
 
Example 16
Project: momo-2   File: Util.java   Source Code and License 5 votes vote down vote up
/**
 * Return a future instant from a string formatted #w#d#h#m
 * @param string String to resolve from
 * @return Instant in the future
 */
public static Instant resolveInstantFromString(String string) {
	Matcher matcher = Pattern.compile("\\d+|[wdhmWDHM]+").matcher(string);
	Instant now = Instant.now();
	LocalDateTime nowLDT = LocalDateTime.ofInstant(now, ZoneId.systemDefault());
	int previous = 0;
	while(matcher.find()) {
		String s = matcher.group().toLowerCase();
		if (Util.isInteger(s)) {
			previous = Integer.parseInt(s);
			continue;
		}
		switch(s) {
		case "w":
			nowLDT = nowLDT.plus(previous, ChronoUnit.WEEKS);
			break;
		case "d":
			nowLDT = nowLDT.plus(previous, ChronoUnit.DAYS);
			break;
		case "h":
			nowLDT = nowLDT.plus(previous, ChronoUnit.HOURS);
			break;
		case "m":
			nowLDT = nowLDT.plus(previous, ChronoUnit.MINUTES);
			break;
		default:
			break;
		}
	}
	return nowLDT.atZone(ZoneId.systemDefault()).toInstant();
}
 
Example 17
Project: OAuth-2.0-Cookbook   File: OpenIDAuthentication.java   Source Code and License 5 votes vote down vote up
public boolean hasExpired() {
    OffsetDateTime expirationDateTime = OffsetDateTime.ofInstant(
            Instant.ofEpochSecond(expirationTime), ZoneId.systemDefault());

    OffsetDateTime now = OffsetDateTime.now(ZoneId.systemDefault());

    return now.isAfter(expirationDateTime);
}
 
Example 18
Project: openjdk-jdk10   File: TCKZonedDateTime.java   Source Code and License 5 votes vote down vote up
@Test(dataProvider="sampleTimes")
public void test_equals_true(int y, int o, int d, int h, int m, int s, int n, ZoneId ignored) {
    ZonedDateTime a = ZonedDateTime.of(dateTime(y, o, d, h, m, s, n), ZONE_0100);
    ZonedDateTime b = ZonedDateTime.of(dateTime(y, o, d, h, m, s, n), ZONE_0100);
    assertEquals(a.equals(b), true);
    assertEquals(a.hashCode() == b.hashCode(), true);
}
 
Example 19
Project: jdk8u-jdk   File: TCKZonedDateTime.java   Source Code and License 5 votes vote down vote up
@Test(dataProvider="IsBefore")
public void test_isBefore(int hour1, int minute1, ZoneId zone1, int hour2, int minute2, ZoneId zone2, boolean expected) {
    ZonedDateTime a = ZonedDateTime.of(2008, 6, 30, hour1, minute1, 0, 0, zone1);
    ZonedDateTime b = ZonedDateTime.of(2008, 6, 30, hour2, minute2, 0, 0, zone2);
    assertEquals(a.isBefore(b), expected);
    assertEquals(b.isBefore(a), false);
    assertEquals(a.isBefore(a), false);
    assertEquals(b.isBefore(b), false);
}
 
Example 20
Project: morpheus-core   File: SparseArrayOfZonedDateTimes.java   Source Code and License 5 votes vote down vote up
@Override
public final ZonedDateTime getValue(int index) {
    this.checkBounds(index, length);
    final long value = values.get(index);
    if (value == nullValue) {
        return null;
    } else {
        final ZoneId zone = zoneIdMap2.get(zoneIds.get(index));
        final Instant instant = Instant.ofEpochMilli(value);
        return ZonedDateTime.ofInstant(instant, zone);
    }
}
 
Example 21
Project: JSK   File: JSKDateConverter.java   Source Code and License 5 votes vote down vote up
/**
 * This method returns the date passed as parameter converted to {@link LocalDateTime}.
 * @param date {@link Date}
 * @return {@link LocalDateTime}
 * @throws JSKException if some of the parameters are null.
 */
public static LocalDateTime dateToLocalDateTime(Date date) throws JSKException {

    if (isNull(date)) {
        throw new JSKException(NULL_PARAMETERS);
    }
    
    return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
}
 
Example 22
Project: jdk8u-jdk   File: TCKZoneIdPrinterParser.java   Source Code and License 5 votes vote down vote up
@Test(dataProvider="parseSuccess")
public void test_parseSuccess_plain(String text, int expectedIndex, int expectedErrorIndex, ZoneId expected) {
    builder.appendZoneId();
    TemporalAccessor parsed = builder.toFormatter().parseUnresolved(text, pos);
    assertEquals(pos.getErrorIndex(), expectedErrorIndex, "Incorrect error index parsing: " + text);
    assertEquals(pos.getIndex(), expectedIndex, "Incorrect index parsing: " + text);
    if (expected != null) {
        assertEquals(parsed.query(TemporalQueries.zoneId()), expected, "Incorrect zoneId parsing: " + text);
        assertEquals(parsed.query(TemporalQueries.offset()), null, "Incorrect offset parsing: " + text);
        assertEquals(parsed.query(TemporalQueries.zone()), expected, "Incorrect zone parsing: " + text);
    } else {
        assertEquals(parsed, null);
    }
}
 
Example 23
Project: JSK   File: JSKDateConverter.java   Source Code and License 5 votes vote down vote up
/**
 * This method returns the date passed as parameter converted to {@link Date}
 * @param date {@link LocalDateTime}
 * @return {@link Date}
 * @throws JSKException if some of the parameters are null.
 */
public static Date dateToDate(LocalDateTime date) throws JSKException {
	
	if (isNull(date)) {
           throw new JSKException(NULL_PARAMETERS);
       }
	
	return Date.from(date.atZone(ZoneId.systemDefault()).toInstant());
}
 
Example 24
Project: openjdk-jdk10   File: TimeZone.java   Source Code and License 5 votes vote down vote up
/**
 * Gets the {@code TimeZone} for the given {@code zoneId}.
 *
 * @param zoneId a {@link ZoneId} from which the time zone ID is obtained
 * @return the specified {@code TimeZone}, or the GMT zone if the given ID
 *         cannot be understood.
 * @throws NullPointerException if {@code zoneId} is {@code null}
 * @since 1.8
 */
public static TimeZone getTimeZone(ZoneId zoneId) {
    String tzid = zoneId.getId(); // throws an NPE if null
    char c = tzid.charAt(0);
    if (c == '+' || c == '-') {
        tzid = "GMT" + tzid;
    } else if (c == 'Z' && tzid.length() == 1) {
        tzid = "UTC";
    }
    return getTimeZone(tzid, true);
}
 
Example 25
Project: openjdk-jdk10   File: TestZoneId.java   Source Code and License 5 votes vote down vote up
public void test_Paris_getOffset_fromDST() {
    ZoneId test = ZoneId.of("Europe/Paris");
    assertEquals(test.getRules().getOffset(createInstant(2008, 10, 24, ZoneOffset.UTC)), ZoneOffset.ofHours(2));
    assertEquals(test.getRules().getOffset(createInstant(2008, 10, 25, ZoneOffset.UTC)), ZoneOffset.ofHours(2));
    assertEquals(test.getRules().getOffset(createInstant(2008, 10, 26, ZoneOffset.UTC)), ZoneOffset.ofHours(2));
    assertEquals(test.getRules().getOffset(createInstant(2008, 10, 27, ZoneOffset.UTC)), ZoneOffset.ofHours(1));
    assertEquals(test.getRules().getOffset(createInstant(2008, 10, 28, ZoneOffset.UTC)), ZoneOffset.ofHours(1));
    assertEquals(test.getRules().getOffset(createInstant(2008, 10, 29, ZoneOffset.UTC)), ZoneOffset.ofHours(1));
    assertEquals(test.getRules().getOffset(createInstant(2008, 10, 30, ZoneOffset.UTC)), ZoneOffset.ofHours(1));
    assertEquals(test.getRules().getOffset(createInstant(2008, 10, 31, ZoneOffset.UTC)), ZoneOffset.ofHours(1));
    // cutover at 01:00Z
    assertEquals(test.getRules().getOffset(createInstant(2008, 10, 26, 0, 59, 59, 999999999, ZoneOffset.UTC)), ZoneOffset.ofHours(2));
    assertEquals(test.getRules().getOffset(createInstant(2008, 10, 26, 1, 0, 0, 0, ZoneOffset.UTC)), ZoneOffset.ofHours(1));
}
 
Example 26
Project: DisCal-Discord-Bot   File: TimeCommand.java   Source Code and License 5 votes vote down vote up
private void calendarTime(MessageReceivedEvent event, GuildSettings settings) {
	try {
		//TODO: Handle multiple calendars...
		CalendarData data = DatabaseManager.getManager().getMainCalendar(event.getGuild().getLongID());

		if (data.getCalendarAddress().equalsIgnoreCase("primary")) {
			//Does not have a calendar.
			Message.sendMessage(MessageManager.getMessage("Creator.Calendar.NoCalendar", settings), event);
		} else {
			Calendar cal;
			if (settings.useExternalCalendar()) {
				cal = CalendarAuth.getCalendarService(settings).calendars().get(data.getCalendarAddress()).execute();
			} else {
				cal = CalendarAuth.getCalendarService().calendars().get(data.getCalendarAddress()).execute();
			}
			LocalDateTime ldt = LocalDateTime.now(ZoneId.of(cal.getTimeZone()));

			//Okay... format and then we can go from there...
			DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy/MM/dd hh:mm:ss a");
			String thisIsTheCorrectTime = format.format(ldt);

			//Build embed and send.
			EmbedBuilder em = new EmbedBuilder();
			em.withAuthorIcon(Main.client.getGuildByID(266063520112574464L).getIconURL());
			em.withAuthorName("DisCal");
			em.withTitle(MessageManager.getMessage("Embed.Time.Title", settings));
			em.appendField(MessageManager.getMessage("Embed.Time.Time", settings), thisIsTheCorrectTime, false);
			em.appendField(MessageManager.getMessage("Embed.Time.TimeZone", settings), cal.getTimeZone(), false);

			em.withFooterText(MessageManager.getMessage("Embed.Time.Footer", settings));
			em.withUrl(CalendarMessageFormatter.getCalendarLink(cal.getId()));
			em.withColor(56, 138, 237);
			Message.sendMessage(em.build(), event);
		}
	} catch (Exception e) {
		ExceptionHandler.sendException(event.getAuthor(), "Failed to connect to Google Cal.", e, this.getClass());
		Message.sendMessage(MessageManager.getMessage("Notification.Error.Unknown", settings), event);
	}
}
 
Example 27
Project: vars-annotation   File: ImageArchiveServiceDecorator.java   Source Code and License 5 votes vote down vote up
/**
 * Creates the textual overlay for the preview image
 * @param copyrightOwner
 * @param framegrab
 * @param imageUploadResults
 * @return  A string array of ext to be overlaid onto an image.
 */
public static String[] createOverlayText(String copyrightOwner, Framegrab framegrab, ImageUploadResults imageUploadResults) {
    final String[] s = new String[4];
    Instant copyrightDate = getCopyrightDate(framegrab);
    int year = copyrightDate.atZone(ZoneId.of("UTC")).get(ChronoField.YEAR);
    imageUploadResults.getUri().toString().replace(".png", ".jpg");
    s[0] = "Copyright " + year + " " +  copyrightOwner;
    s[1] = imageUploadResults.getUri().toString();
    s[2] = copyrightDate.toString();
    s[3] = "";

    return s;
}
 
Example 28
Project: OpenJSharp   File: DateTimeFormatter.java   Source Code and License 5 votes vote down vote up
/**
 * Constructor.
 *
 * @param printerParser  the printer/parser to use, not null
 * @param locale  the locale to use, not null
 * @param decimalStyle  the DecimalStyle to use, not null
 * @param resolverStyle  the resolver style to use, not null
 * @param resolverFields  the fields to use during resolving, null for all fields
 * @param chrono  the chronology to use, null for no override
 * @param zone  the zone to use, null for no override
 */
DateTimeFormatter(CompositePrinterParser printerParser,
        Locale locale, DecimalStyle decimalStyle,
        ResolverStyle resolverStyle, Set<TemporalField> resolverFields,
        Chronology chrono, ZoneId zone) {
    this.printerParser = Objects.requireNonNull(printerParser, "printerParser");
    this.resolverFields = resolverFields;
    this.locale = Objects.requireNonNull(locale, "locale");
    this.decimalStyle = Objects.requireNonNull(decimalStyle, "decimalStyle");
    this.resolverStyle = Objects.requireNonNull(resolverStyle, "resolverStyle");
    this.chrono = chrono;
    this.zone = zone;
}
 
Example 29
Project: GoupilBot   File: DateTimeLib.java   Source Code and License 5 votes vote down vote up
/**
 * 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 30
Project: spring-io   File: AuditResource.java   Source Code and License 5 votes vote down vote up
/**
 * GET  /audits : get a page of AuditEvents between the fromDate and toDate.
 *
 * @param fromDate the start of the time period of AuditEvents to get
 * @param toDate the end of the time period of AuditEvents to get
 * @param pageable the pagination information
 * @return the ResponseEntity with status 200 (OK) and the list of AuditEvents in body
 */
@GetMapping(params = {"fromDate", "toDate"})
public ResponseEntity<List<AuditEvent>> getByDates(
    @RequestParam(value = "fromDate") LocalDate fromDate,
    @RequestParam(value = "toDate") LocalDate toDate,
    @ApiParam Pageable pageable) {

    Page<AuditEvent> page = auditEventService.findByDates(
        fromDate.atStartOfDay(ZoneId.systemDefault()).toInstant(),
        toDate.atStartOfDay(ZoneId.systemDefault()).plusDays(1).toInstant(),
        pageable);
    HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/management/audits");
    return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}
 
Example 31
Project: git-rekt   File: BookingService.java   Source Code and License 5 votes vote down vote up
/**
 * Calculates and returns the cancellation fee that should be assessed when a user cancels a
 * booking.
 *
 * This method uses the new Java 8 Time API, which a little confusing at first, but way more
 * useful (and easier to use) than the nightmarish way things used to be done.
 *
 * It does NOT account for time zones, since in the real world, this code would be running
 * server side, not client side, and then time zones would not matter.
 *
 * Sadly, the new Java Time and Date API is almost laughably annoying in that there is NO built
 * in easy way to transform an existing Java Date object into a new time api date object,
 * excepting the toInstant method, which brings with it it's own cluttered bag of complications.
 * Why?!?
 *
 * @param booking The booking to calculate cancellation fees for.
 *
 * @return The cancellation fee to cancel the provided booking.
 */
public static double calcCancellationFee(Booking booking) {
    // Define some useful dates for our calculations
    LocalDate today = LocalDate.now();
    Date temp = booking.getCheckInDate();
    ZonedDateTime zdt = Instant.ofEpochMilli(temp.getTime()).atZone(ZoneId.systemDefault());
    LocalDate checkInDate = zdt.toLocalDate();
    temp = booking.getCreatedDate();
    zdt = Instant.ofEpochMilli(temp.getTime()).atZone(ZoneId.systemDefault());
    LocalDate bookingCreationDate = LocalDate.from(zdt);
    long daysTillCheckIn = today.until(checkInDate, ChronoUnit.DAYS);

    // Determine the fee percentage based on specifications
    double feePercentage;
    if(bookingCreationDate.plusDays(2).isAfter(today)) {
        feePercentage = 0.00;
    } else if(daysTillCheckIn > 30) {
        feePercentage = 20.00;
    } else if(daysTillCheckIn > 7) {
        feePercentage = 30.00;
    } else {
        feePercentage = 60.00;
    }

    // Calculate the fee from the bill and the fee percentage
    double fee = 0.00;

    for(BillItem item : booking.getBill().getCharges()) {
        double totalItemPrice = item.getTotalPrice();
        // Check for cases where another discount is applied, etc.
        if(item.getTotalPrice() > 0) {
            fee += (totalItemPrice * feePercentage);
        }
    }

    return fee;
}
 
Example 32
Project: openjdk-jdk10   File: TestZoneId.java   Source Code and License 5 votes vote down vote up
public void test_NewYork_getOffsetInfo() {
    ZoneId test = ZoneId.of("America/New_York");
    checkOffset(test.getRules(), createLDT(2008, 1, 1), ZoneOffset.ofHours(-5), 1);
    checkOffset(test.getRules(), createLDT(2008, 2, 1), ZoneOffset.ofHours(-5), 1);
    checkOffset(test.getRules(), createLDT(2008, 3, 1), ZoneOffset.ofHours(-5), 1);
    checkOffset(test.getRules(), createLDT(2008, 4, 1), ZoneOffset.ofHours(-4), 1);
    checkOffset(test.getRules(), createLDT(2008, 5, 1), ZoneOffset.ofHours(-4), 1);
    checkOffset(test.getRules(), createLDT(2008, 6, 1), ZoneOffset.ofHours(-4), 1);
    checkOffset(test.getRules(), createLDT(2008, 7, 1), ZoneOffset.ofHours(-4), 1);
    checkOffset(test.getRules(), createLDT(2008, 8, 1), ZoneOffset.ofHours(-4), 1);
    checkOffset(test.getRules(), createLDT(2008, 9, 1), ZoneOffset.ofHours(-4), 1);
    checkOffset(test.getRules(), createLDT(2008, 10, 1), ZoneOffset.ofHours(-4), 1);
    checkOffset(test.getRules(), createLDT(2008, 11, 1), ZoneOffset.ofHours(-4), 1);
    checkOffset(test.getRules(), createLDT(2008, 12, 1), ZoneOffset.ofHours(-5), 1);
    checkOffset(test.getRules(), createLDT(2008, 1, 28), ZoneOffset.ofHours(-5), 1);
    checkOffset(test.getRules(), createLDT(2008, 2, 28), ZoneOffset.ofHours(-5), 1);
    checkOffset(test.getRules(), createLDT(2008, 3, 28), ZoneOffset.ofHours(-4), 1);
    checkOffset(test.getRules(), createLDT(2008, 4, 28), ZoneOffset.ofHours(-4), 1);
    checkOffset(test.getRules(), createLDT(2008, 5, 28), ZoneOffset.ofHours(-4), 1);
    checkOffset(test.getRules(), createLDT(2008, 6, 28), ZoneOffset.ofHours(-4), 1);
    checkOffset(test.getRules(), createLDT(2008, 7, 28), ZoneOffset.ofHours(-4), 1);
    checkOffset(test.getRules(), createLDT(2008, 8, 28), ZoneOffset.ofHours(-4), 1);
    checkOffset(test.getRules(), createLDT(2008, 9, 28), ZoneOffset.ofHours(-4), 1);
    checkOffset(test.getRules(), createLDT(2008, 10, 28), ZoneOffset.ofHours(-4), 1);
    checkOffset(test.getRules(), createLDT(2008, 11, 28), ZoneOffset.ofHours(-5), 1);
    checkOffset(test.getRules(), createLDT(2008, 12, 28), ZoneOffset.ofHours(-5), 1);
}
 
Example 33
Project: xitikit-blue   File: UtcUnixDateDeserializer.java   Source Code and License 5 votes vote down vote up
/**
 * Converts the value from the DeserializationContext
 * to a LocalDateTime.
 *
 * Assumes the value being passed is a Long with a value that
 * represents the number of seconds since January 1 2017.
 *
 * @param jsonParser JsonParser
 * @param deserializationContext DeserializationContext
 *
 * @return ZonedDateTime
 *
 * @throws IOException when the value cannot be read, or is improperly formatted.
 */
@Override
public ZonedDateTime deserialize(
  final JsonParser jsonParser,
  final DeserializationContext deserializationContext) throws IOException{

    return Instant
      .ofEpochSecond(
        deserializationContext
          .readValue(
            jsonParser,
            Long.class))
      .atZone(
        ZoneId.systemDefault());
}
 
Example 34
Project: gdl2   File: Interpreter.java   Source Code and License 5 votes vote down vote up
private double convertObjectValueToDouble(Object dataValue) {
    if (dataValue instanceof DvQuantity) { // TODO handle units
        return Double.valueOf(evaluateQuantityValue((DvQuantity) dataValue).toString());
    } else if (dataValue instanceof DvDateTime) {
        return ((DvDateTime) dataValue).getDateTime().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
    } else if (dataValue instanceof LocalDateTime) {
        return ((LocalDateTime) dataValue).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
    } else if (dataValue.toString().startsWith("(-") && dataValue.toString().endsWith(")")) {
        int length = dataValue.toString().length();
        return Double.valueOf(dataValue.toString().substring(1, length - 1));
    } else {
        return Double.valueOf(dataValue.toString());
    }
}
 
Example 35
Project: ReqMan   File: MilestonePropertiesScene.java   Source Code and License 5 votes vote down vote up
public void handleSaving(ActionEvent event) {
    String name = (tfName.getText() == null || tfName.getText().isEmpty()) ? "Milestone" : tfName.getText(); // Default name
    Date d = null;
    if (inputDate.getValue() != null) {
        d = Date.from(inputDate.getValue().atStartOfDay(ZoneId.systemDefault()).toInstant());
    }

    milestone = new Milestone(name, 0, d);// ordinal is handled later
    getWindow().hide();
}
 
Example 36
Project: openjdk-jdk10   File: ZipUtils.java   Source Code and License 5 votes vote down vote up
public static long javaToDosTime(long time) {
    Instant instant = Instant.ofEpochMilli(time);
    LocalDateTime ldt = LocalDateTime.ofInstant(
            instant, ZoneId.systemDefault());
    int year = ldt.getYear() - 1980;
    if (year < 0) {
        return (1 << 21) | (1 << 16);
    }
    return (year << 25 |
        ldt.getMonthValue() << 21 |
        ldt.getDayOfMonth() << 16 |
        ldt.getHour() << 11 |
        ldt.getMinute() << 5 |
        ldt.getSecond() >> 1) & 0xffffffffL;
}
 
Example 37
Project: mot-public-api   File: MotrReadServiceTest.java   Source Code and License 5 votes vote down vote up
@Test
public void getLatestMotTestByRegistration_ValidRegistration_NullTest() {

    final String registration = "AA00AAA";
    final LocalDateTime manufactureDateTime = LocalDateTime.now().minus(5, ChronoUnit.YEARS);
    final int manufactureYear = manufactureDateTime.getYear();
    final Date manufactureDate = Date.from(manufactureDateTime.atZone(ZoneId.systemDefault()).toInstant());
    final String make = "MADEBY";
    final String model = "ETERNIA";
    final String primaryColour = "BLUE";
    final String secondaryColour = "WHITE";

    final Vehicle backendVehicle = new Vehicle();
    backendVehicle.setRegistration(registration);
    backendVehicle.setManufactureDate(manufactureDate);
    backendVehicle.setMake(make);
    backendVehicle.setModel(model);
    backendVehicle.setPrimaryColour(primaryColour);
    backendVehicle.setSecondaryColour(secondaryColour);

    uk.gov.dvsa.mot.trade.api.DvlaVehicle dvlaVehicle = createDvlaVehicle();

    when(vehicleReadServiceMock.findByRegistration(registration)).thenReturn(Arrays.asList(backendVehicle));
    when(motTestReadServiceMock.getLatestMotTestPassByVehicle(backendVehicle)).thenReturn(null);
    when(vehicleReadServiceMock.findDvlaVehicleByRegistration(registration)).thenReturn(Arrays.asList(dvlaVehicle));

    MotrResponse motrResponse = motrReadService.getLatestMotTestByRegistration(registration);

    assertNotNull("Returned vehicle is null", motrResponse);
    assertEquals("Registration is incorrect", registration, motrResponse.getRegistration());
    assertEquals("Make is incorrect", make, motrResponse.getMake());
    assertEquals("Model is incorrect", model, motrResponse.getModel());
    assertEquals("Manufacturing year is incorrect", Integer.toString(manufactureYear),
            motrResponse.getManufactureYear());
    assertNotNull("Test expiry date is incorrect", motrResponse.getMotTestExpiryDate());
    assertNull("Test number is incorrect", motrResponse.getMotTestNumber());
    assertEquals("Primary colour is incorrect", primaryColour, motrResponse.getPrimaryColour());
    assertEquals("Secondary colour is incorrect", secondaryColour, motrResponse.getSecondaryColour());

}
 
Example 38
Project: testing_security_development_enterprise_systems   File: UserTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testRegisteredBeforeBeingBorn(){
    User user = getAValidUser();
    user.setDateOfBirth(Date.from(LocalDate.of(1980, 1, 1).atStartOfDay(ZoneId.systemDefault()).toInstant()));
    user.setDateOfRegistration(Date.from(LocalDate.of(1970, 1, 1).atStartOfDay(ZoneId.systemDefault()).toInstant()));

    assertTrue(hasViolations(user));
    assertFalse(persistInATransaction(user));
}
 
Example 39
Project: openjdk-jdk10   File: TestExampleCode.java   Source Code and License 5 votes vote down vote up
void HijrahExample1() {
    HijrahDate hd2 = HijrahChronology.INSTANCE.date(1200, 1, 1);

    ChronoLocalDateTime<HijrahDate> hdt = hd2.atTime(LocalTime.MIDNIGHT);
    ChronoZonedDateTime<HijrahDate> zhdt = hdt.atZone(ZoneId.of("GMT"));
    HijrahDate hd3 = zhdt.toLocalDate();
    ChronoLocalDateTime<HijrahDate> hdt2 = zhdt.toLocalDateTime();
    HijrahDate hd4 = hdt2.toLocalDate();

    HijrahDate hd5 = next(hd2);
}
 
Example 40
Project: jdk8u-jdk   File: JavatimeTest.java   Source Code and License 5 votes vote down vote up
private static void print(LocalDateTime ldt, Timestamp ts) {
    ZonedDateTime zdt = ZonedDateTime.of(ldt, ZoneId.systemDefault());
    System.out.printf("ldt:ts  %d/%d, %d/%d, %d/%d, %d/%d, %d/%d, %d/%d, nano:[%d/%d]%n",
           zdt.getYear(), ts.getYear() + 1900,
           zdt.getMonthValue(), ts.getMonth() + 1,
           zdt.getDayOfMonth(), ts.getDate(),
           zdt.getHour(), ts.getHours(),
           zdt.getMinute(), ts.getMinutes(),
           zdt.getSecond(), ts.getSeconds(),
           zdt.getNano(), ts.getNanos());
}
 
Example 41
Project: Hydrograph   File: DateFunctions.java   Source Code and License 5 votes vote down vote up
/**
 * Returns date with {@code years} added to {@code date}
 *
 * @param date       the date to which months are to be added
 * @param years years to be added to given {@code date}
 * @return date after adding  years to it
 * if {@code date} is null return null
 */
public static Date addYearsToDate(Date date, int years) {

    if (date == null)
        return null;
    Date localDate = new Date(date.getTime());

    LocalDateTime localDateTime = LocalDateTime.ofInstant(localDate.toInstant(), ZoneId.systemDefault());
    Date newDate = Date.from(localDateTime.plusYears((long) years).atZone(ZoneId.systemDefault()).toInstant());
    return newDate;
}
 
Example 42
Project: CalendarFX   File: CalendarTest.java   Source Code and License 5 votes vote down vote up
@Before
public void setup() {
    LocalDate today = LocalDate.now();
    recurrenceSourceEntry = new Entry<>("Recurrence Source");
    recurrenceSourceEntry.setInterval(recurrenceSourceEntry.getInterval().withEndDate(LocalDate.now().plusDays(30)));
    recurrenceSourceEntry.setRecurrenceRule("RRULE:FREQ=DAILY;");
    recurrenceSourceEntry.setCalendar(calendar);
    Map<LocalDate, List<Entry<?>>> entries = calendar.findEntries(today, today, ZoneId.systemDefault());
    recurrence = (Entry<String>) entries.get(today).get(0);
}
 
Example 43
Project: jdk8u-jdk   File: TCKChronoZonedDateTime.java   Source Code and License 5 votes vote down vote up
@Test(dataProvider="calendars")
public void test_from_TemporalAccessor(Chronology chrono) {
    ZonedDateTime refDateTime = ZonedDateTime.of(2013, 1, 1, 12, 30, 0, 0, ZoneId.of("Europe/Paris"));
    ChronoZonedDateTime<?> dateTime = chrono.zonedDateTime(refDateTime);
    ChronoZonedDateTime<?> test1 = ChronoZonedDateTime.from(dateTime);
    assertEquals(test1, dateTime);
}
 
Example 44
Project: chunk-logger   File: ChunkListOfPlayers.java   Source Code and License 5 votes vote down vote up
public void readFromNBT(NBTTagList listOfPlayers) {
	int howManyTimesToLoop = listOfPlayers.tagCount();
	for (int i = 0; i < howManyTimesToLoop; i++) {
		NBTTagCompound nbt = listOfPlayers.getCompoundTagAt(i);
		LocalDateTime enterTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(nbt.getLong("enterTime")), ZoneId.systemDefault());
		UUID player = nbt.getUniqueId("PlayerUUID");
		if (nbt.getBoolean("HasLeft")) {
			LocalDateTime leaveTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(nbt.getLong("LeaveTime")), ZoneId.systemDefault());
			Duration stayTime = Duration.ofMillis(nbt.getLong("StayTime"));
			playersInChunk.add(new PlayerInChunk(enterTime, leaveTime, stayTime, player));
		} else {
			playersInChunk.add(new PlayerInChunk(enterTime, player));
		}
	}
}
 
Example 45
Project: e-identification-tupas-idp-public   File: SessionParserServiceRequestTest.java   Source Code and License 5 votes vote down vote up
@Test
public void createInitResultPreventsAdptTStampInjection() throws Exception {
    ReflectionTestUtils.setField(parser, "clock", Clock.fixed(Instant.ofEpochSecond(1489485600), ZoneId.systemDefault()));
    when(authenticationHandlerUtils.createToken()).thenReturn("000000");
    when(tupasStampIdService.getTupasStampCounter(anyInt())).thenReturn("0000001");
    MultivaluedMap<String, String> requestParamsWithInjection = new MultivaluedHashMap<>();
    requestParamsWithInjection.add("declRef", "nordea.tfi.tupas.fi");
    requestParamsWithInjection.add("ckey", "e1s1");
    requestParamsWithInjection.add("lang", "fi");
    requestParamsWithInjection.add("ADPT_TSTAMP", "INJECTED");
    String initResult = parser.createInitResult(requestParamsWithInjection);
    assertFalse(initResult.contains("INJECTED"));
}
 
Example 46
Project: jdk8u-jdk   File: TestZoneId.java   Source Code and License 5 votes vote down vote up
public void test_London_getOffsetInfo_fromDST() {
    ZoneId test = ZoneId.of("Europe/London");
    checkOffset(test.getRules(), createLDT(2008, 10, 24), ZoneOffset.ofHours(1), 1);
    checkOffset(test.getRules(), createLDT(2008, 10, 25), ZoneOffset.ofHours(1), 1);
    checkOffset(test.getRules(), createLDT(2008, 10, 26), ZoneOffset.ofHours(1), 1);
    checkOffset(test.getRules(), createLDT(2008, 10, 27), ZoneOffset.ofHours(0), 1);
    checkOffset(test.getRules(), createLDT(2008, 10, 28), ZoneOffset.ofHours(0), 1);
    checkOffset(test.getRules(), createLDT(2008, 10, 29), ZoneOffset.ofHours(0), 1);
    checkOffset(test.getRules(), createLDT(2008, 10, 30), ZoneOffset.ofHours(0), 1);
    checkOffset(test.getRules(), createLDT(2008, 10, 31), ZoneOffset.ofHours(0), 1);
    // cutover at 01:00Z
    checkOffset(test.getRules(), LocalDateTime.of(2008, 10, 26, 0, 59, 59, 999999999), ZoneOffset.ofHours(1), 1);
    checkOffset(test.getRules(), LocalDateTime.of(2008, 10, 26, 1, 30, 0, 0), ZoneOffset.ofHours(1), OVERLAP);
    checkOffset(test.getRules(), LocalDateTime.of(2008, 10, 26, 2, 0, 0, 0), ZoneOffset.ofHours(0), 1);
}
 
Example 47
Project: codemotion-2017-taller-de-jhipster   File: AuditResource.java   Source Code and License 5 votes vote down vote up
/**
 * GET  /audits : get a page of AuditEvents between the fromDate and toDate.
 *
 * @param fromDate the start of the time period of AuditEvents to get
 * @param toDate the end of the time period of AuditEvents to get
 * @param pageable the pagination information
 * @return the ResponseEntity with status 200 (OK) and the list of AuditEvents in body
 */
@GetMapping(params = {"fromDate", "toDate"})
public ResponseEntity<List<AuditEvent>> getByDates(
    @RequestParam(value = "fromDate") LocalDate fromDate,
    @RequestParam(value = "toDate") LocalDate toDate,
    @ApiParam Pageable pageable) {

    Page<AuditEvent> page = auditEventService.findByDates(
        fromDate.atStartOfDay(ZoneId.systemDefault()).toInstant(),
        toDate.atStartOfDay(ZoneId.systemDefault()).plusDays(1).toInstant(),
        pageable);
    HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/management/audits");
    return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}
 
Example 48
Project: CalendarFX   File: ZonedDateTimeIteratorFactory.java   Source Code and License 4 votes vote down vote up
@Override
public void advanceTo(ZonedDateTime d) {
    ZonedDateTime dUtc = d.withZoneSameInstant(ZoneId.of("UTC"));
    it.advanceTo(zonedDateTimeToDateValue(dUtc));
}
 
Example 49
Project: openjdk-jdk10   File: TCKLocalDateTime.java   Source Code and License 4 votes vote down vote up
@Test(expectedExceptions=NullPointerException.class)
public void test_atZone_nullTimeZone() {
    LocalDateTime t = LocalDateTime.of(2008, 6, 30, 11, 30);
    t.atZone((ZoneId) null);
}
 
Example 50
Project: Shadbot   File: TimeUtils.java   Source Code and License 4 votes vote down vote up
public static LocalDateTime toLocalDate(Instant instant) {
	return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
}
 
Example 51
Project: Supreme-Bot   File: Standard.java   Source Code and License 4 votes vote down vote up
public static final ZoneId getUTC() {
    return UTC;
}
 
Example 52
Project: GitHub   File: ZoneIdTest.java   Source Code and License 4 votes vote down vote up
public ZoneId getDate() {
    return date;
}
 
Example 53
Project: jdk8u-jdk   File: HijrahChronology.java   Source Code and License 4 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public ChronoZonedDateTime<HijrahDate> zonedDateTime(Instant instant, ZoneId zone) {
    return (ChronoZonedDateTime<HijrahDate>) super.zonedDateTime(instant, zone);
}
 
Example 54
Project: java-logging   File: FakeClock.java   Source Code and License 4 votes vote down vote up
@Override
public Clock withZone(ZoneId zone) {
    return null;
}
 
Example 55
Project: Simplify-Core   File: ObjectToDateCodec.java   Source Code and License 4 votes vote down vote up
public Date convertObjectToDate(String date, String pattern) {
    return Date.from(LocalDateTime.parse(date, DateTimeFormatter.ofPattern(pattern)).atZone(ZoneId.systemDefault()).toInstant());
}
 
Example 56
Project: nixmash-blog   File: ZoneDateTimeConverter.java   Source Code and License 4 votes vote down vote up
@Override
public ZonedDateTime convertToEntityAttribute(java.sql.Timestamp databaseValue) {
    LocalDateTime localDateTime = databaseValue.toLocalDateTime();
    return localDateTime.atZone(ZoneId.systemDefault());
}
 
Example 57
Project: openjdk-jdk10   File: TCKZonedDateTime.java   Source Code and License 4 votes vote down vote up
@Test
public void factory_parse_formatter() {
    DateTimeFormatter f = DateTimeFormatter.ofPattern("y M d H m s VV");
    ZonedDateTime test = ZonedDateTime.parse("2010 12 3 11 30 0 Europe/London", f);
    assertEquals(test, ZonedDateTime.of(LocalDateTime.of(2010, 12, 3, 11, 30), ZoneId.of("Europe/London")));
}
 
Example 58
Project: vertx-zero   File: Period.java   Source Code and License 4 votes vote down vote up
public static Date parse(final LocalTime time) {
    final LocalDate date = LocalDate.now();
    final LocalDateTime datetime = LocalDateTime.of(date, time);
    return Date.from(datetime.atZone(ZoneId.systemDefault()).toInstant());
}
 
Example 59
Project: xcalendar   File: XCalendarYearWidget.java   Source Code and License 4 votes vote down vote up
/**
 * 
 */
@Override
protected <T> T query(XVirtualCalendar c, ZoneId z, int col, int row) {
	int idx = row * 4 + col; return cast(c.getDecade().getValue1() + idx); 
}
 
Example 60
Project: holon-vaadin   File: DateToLocalDateConverter.java   Source Code and License 4 votes vote down vote up
/**
 * Gets the Time zone to use for conversion
 * @return the timeZone Time zone to use for conversion
 */
@Override
public ZoneId getTimeZone() {
	return timeZone;
}