Java 类java.time.ZoneId 实例源码

项目:jdk8u-jdk    文件:TestZoneId.java   
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());
}
项目:device-opcua-java    文件:ScheduleContext.java   
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;
}
项目:morpheus-core    文件:Formats.java   
/**
 * 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));
}
项目:morpheus-core    文件:FormatsTest.java   
@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);
}
项目:git-rekt    文件:BrowseRoomsScreenController.java   
/**
 * 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));
}
项目:CalendarFX    文件:DateControlSkin.java   
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;
    }
项目:bouncr    文件:SignInService.java   
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;
}
项目:ABC-List    文件:DateConverterTest.java   
@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);
}
项目:gdl2    文件:Interpreter.java   
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);
}
项目:morpheus-core    文件:RangeSplitTests.java   
@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");
        }
    }
}
项目:jdk8u-jdk    文件:TCKZoneIdPrinterParser.java   
@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);
    }
}
项目:galop    文件:ResponseBuilder.java   
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);

    }
项目:galop    文件:ResponseBuilderTest.java   
@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));

}
项目:morpheus-core    文件:DenseArrayOfZonedDateTimes.java   
@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;
        }
    }
}
项目:cactoos    文件:DateAsText.java   
/**
 * 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)
    );
}
项目:momo-2    文件:Util.java   
/**
 * 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();
}
项目:OAuth-2.0-Cookbook    文件:OpenIDAuthentication.java   
public boolean hasExpired() {
    OffsetDateTime expirationDateTime = OffsetDateTime.ofInstant(
            Instant.ofEpochSecond(expirationTime), ZoneId.systemDefault());

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

    return now.isAfter(expirationDateTime);
}
项目:openjdk-jdk10    文件:TCKZonedDateTime.java   
@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);
}
项目:jdk8u-jdk    文件:TCKZonedDateTime.java   
@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);
}
项目:morpheus-core    文件:SparseArrayOfZonedDateTimes.java   
@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);
    }
}
项目:JSK    文件:JSKDateConverter.java   
/**
 * 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());
}
项目:jdk8u-jdk    文件:TCKZoneIdPrinterParser.java   
@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);
    }
}
项目:JSK    文件:JSKDateConverter.java   
/**
 * 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());
}
项目:openjdk-jdk10    文件:TimeZone.java   
/**
 * 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);
}
项目:openjdk-jdk10    文件:TestZoneId.java   
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));
}
项目:DisCal-Discord-Bot    文件:TimeCommand.java   
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);
    }
}
项目:vars-annotation    文件:ImageArchiveServiceDecorator.java   
/**
 * 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;
}
项目:OpenJSharp    文件:DateTimeFormatter.java   
/**
 * 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;
}
项目:GoupilBot    文件:DateTimeLib.java   
/**
 * 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;
  }
}
项目:spring-io    文件:AuditResource.java   
/**
 * 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);
}
项目:git-rekt    文件:BookingService.java   
/**
 * 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;
}
项目:openjdk-jdk10    文件:TestZoneId.java   
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);
}
项目:xitikit-blue    文件:UtcUnixDateDeserializer.java   
/**
 * 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());
}
项目:gdl2    文件:Interpreter.java   
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());
    }
}
项目:ReqMan    文件:MilestonePropertiesScene.java   
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();
}
项目:openjdk-jdk10    文件:ZipUtils.java   
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;
}
项目:mot-public-api    文件:MotrReadServiceTest.java   
@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());

}
项目:testing_security_development_enterprise_systems    文件:UserTest.java   
@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));
}
项目:openjdk-jdk10    文件:TestExampleCode.java   
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);
}
项目:jdk8u-jdk    文件:JavatimeTest.java   
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());
}