Java 类org.joda.time.DateTimeZone 实例源码

项目:soundwave    文件:DailyInstanceCountPerTypeJob.java   
private Boolean calculateDailyInstanceCounts() {

    try {

      DateTime utcNow = DateTime.now(DateTimeZone.UTC);

      List<Instance> instances = cloudInstanceStore.getInstances(region);
      List<ReservedInstances> reservedInstances = cloudInstanceStore.getReservedInstances(region);

      // Generate instance counts per type per Availability zone
      List<EsInstanceCountRecord> instanceCountRecords =
          getInstanceCountRecords(instances, reservedInstances, utcNow);
      logger.info("Number of instance count records {}", instanceCountRecords.size());

      // Insert records into soundwave store.
      instanceCounterStore.bulkInsert(instanceCountRecords);
      logger.info("Bulk insert succeeded for instance count records");

      return true;

    } catch (Exception e) {

      logger.error(ExceptionUtils.getRootCauseMessage(e));
      return false;
    }
  }
项目:kubernetes-elastic-agents    文件:KubernetesInstanceFactory.java   
public KubernetesInstance fromKubernetesPod(Pod elasticAgentPod) {
    KubernetesInstance kubernetesInstance;
    try {
        ObjectMeta metadata = elasticAgentPod.getMetadata();
        DateTime createdAt = DateTime.now().withZone(DateTimeZone.UTC);
        if (StringUtils.isNotBlank(metadata.getCreationTimestamp())) {
            createdAt = new DateTime(getSimpleDateFormat().parse(metadata.getCreationTimestamp())).withZone(DateTimeZone.UTC);
        }
        String environment = metadata.getLabels().get(Constants.ENVIRONMENT_LABEL_KEY);
        Long jobId = Long.valueOf(metadata.getLabels().get(Constants.JOB_ID_LABEL_KEY));
        kubernetesInstance = new KubernetesInstance(createdAt, environment, metadata.getName(), metadata.getAnnotations(), jobId, PodState.fromPod(elasticAgentPod));
    } catch (ParseException e) {
        throw new RuntimeException(e);
    }
    return kubernetesInstance;
}
项目:elasticsearch_my    文件:DateMathParser.java   
public long parse(String text, LongSupplier now, boolean roundUp, DateTimeZone timeZone) {
    long time;
    String mathString;
    if (text.startsWith("now")) {
        try {
            time = now.getAsLong();
        } catch (Exception e) {
            throw new ElasticsearchParseException("could not read the current timestamp", e);
        }
        mathString = text.substring("now".length());
    } else {
        int index = text.indexOf("||");
        if (index == -1) {
            return parseDateTime(text, timeZone, roundUp);
        }
        time = parseDateTime(text.substring(0, index), timeZone, false);
        mathString = text.substring(index + 2);
    }

    return parseMath(mathString, time, roundUp, timeZone);
}
项目:elasticsearch_my    文件:TimeZoneRoundingTests.java   
/**
 * perform a number on assertions and checks on {@link TimeUnitRounding} intervals
 * @param rounded the expected low end of the rounding interval
 * @param unrounded a date in the interval to be checked for rounding
 * @param nextRoundingValue the expected upper end of the rounding interval
 * @param rounding the rounding instance
 */
private static void assertInterval(long rounded, long unrounded, long nextRoundingValue, Rounding rounding,
        DateTimeZone tz) {
    assert rounded <= unrounded && unrounded <= nextRoundingValue;
    assertThat("rounding should be idempotent ", rounding.round(rounded), isDate(rounded, tz));
    assertThat("rounded value smaller or equal than unrounded" + rounding, rounded, lessThanOrEqualTo(unrounded));
    assertThat("values less than rounded should round further down" + rounding, rounding.round(rounded - 1), lessThan(rounded));
    assertThat("nextRounding value should be greater than date" + rounding, nextRoundingValue, greaterThan(unrounded));
    assertThat("nextRounding value should be a rounded date", rounding.round(nextRoundingValue), isDate(nextRoundingValue, tz));
    assertThat("values above nextRounding should round down there", rounding.round(nextRoundingValue + 1),
            isDate(nextRoundingValue, tz));

    long dateBetween = dateBetween(rounded, nextRoundingValue);
    assertThat("dateBetween should round down to roundedDate", rounding.round(dateBetween), isDate(rounded, tz));
    assertThat("dateBetween should round up to nextRoundingValue", rounding.nextRoundingValue(dateBetween),
            isDate(nextRoundingValue, tz));
}
项目:elasticsearch_my    文件:SearchQueryIT.java   
public void testDateRangeInQueryStringWithTimeZone_7880() {
    //the mapping needs to be provided upfront otherwise we are not sure how many failures we get back
    //as with dynamic mappings some shards might be lacking behind and parse a different query
    assertAcked(prepareCreate("test").addMapping(
            "type", "past", "type=date"
    ));

    DateTimeZone timeZone = randomDateTimeZone();
    String now = ISODateTimeFormat.dateTime().print(new DateTime(timeZone));
    logger.info(" --> Using time_zone [{}], now is [{}]", timeZone.getID(), now);
    client().prepareIndex("test", "type", "1").setSource("past", now).get();
    refresh();

    SearchResponse searchResponse = client().prepareSearch().setQuery(queryStringQuery("past:[now-1m/m TO now+1m/m]")
            .timeZone(timeZone.getID())).get();
    assertHitCount(searchResponse, 1L);
}
项目:elasticsearch_my    文件:SimpleJodaTests.java   
public void testRoundingWithTimeZone() {
    MutableDateTime time = new MutableDateTime(DateTimeZone.UTC);
    time.setZone(DateTimeZone.forOffsetHours(-2));
    time.setRounding(time.getChronology().dayOfMonth(), MutableDateTime.ROUND_FLOOR);

    MutableDateTime utcTime = new MutableDateTime(DateTimeZone.UTC);
    utcTime.setRounding(utcTime.getChronology().dayOfMonth(), MutableDateTime.ROUND_FLOOR);

    time.setMillis(utcTimeInMillis("2009-02-03T01:01:01"));
    utcTime.setMillis(utcTimeInMillis("2009-02-03T01:01:01"));

    assertThat(time.toString(), equalTo("2009-02-02T00:00:00.000-02:00"));
    assertThat(utcTime.toString(), equalTo("2009-02-03T00:00:00.000Z"));
    // the time is on the 2nd, and utcTime is on the 3rd, but, because time already encapsulates
    // time zone, the millis diff is not 24, but 22 hours
    assertThat(time.getMillis(), equalTo(utcTime.getMillis() - TimeValue.timeValueHours(22).millis()));

    time.setMillis(utcTimeInMillis("2009-02-04T01:01:01"));
    utcTime.setMillis(utcTimeInMillis("2009-02-04T01:01:01"));
    assertThat(time.toString(), equalTo("2009-02-03T00:00:00.000-02:00"));
    assertThat(utcTime.toString(), equalTo("2009-02-04T00:00:00.000Z"));
    assertThat(time.getMillis(), equalTo(utcTime.getMillis() - TimeValue.timeValueHours(22).millis()));
}
项目:elasticsearch_my    文件:DateMathIndexExpressionsIntegrationIT.java   
public void testAutoCreateIndexWithDateMathExpression() throws Exception {
    DateTime now = new DateTime(DateTimeZone.UTC);
    String index1 = ".marvel-" + DateTimeFormat.forPattern("YYYY.MM.dd").print(now);
    String index2 = ".marvel-" + DateTimeFormat.forPattern("YYYY.MM.dd").print(now.minusDays(1));
    String index3 = ".marvel-" + DateTimeFormat.forPattern("YYYY.MM.dd").print(now.minusDays(2));

    String dateMathExp1 = "<.marvel-{now/d}>";
    String dateMathExp2 = "<.marvel-{now/d-1d}>";
    String dateMathExp3 = "<.marvel-{now/d-2d}>";
    client().prepareIndex(dateMathExp1, "type", "1").setSource("{}", XContentType.JSON).get();
    client().prepareIndex(dateMathExp2, "type", "2").setSource("{}", XContentType.JSON).get();
    client().prepareIndex(dateMathExp3, "type", "3").setSource("{}", XContentType.JSON).get();
    refresh();

    SearchResponse searchResponse = client().prepareSearch(dateMathExp1, dateMathExp2, dateMathExp3).get();
    assertHitCount(searchResponse, 3);
    assertSearchHits(searchResponse, "1", "2", "3");

    IndicesStatsResponse indicesStatsResponse = client().admin().indices().prepareStats(dateMathExp1, dateMathExp2, dateMathExp3).get();
    assertThat(indicesStatsResponse.getIndex(index1), notNullValue());
    assertThat(indicesStatsResponse.getIndex(index2), notNullValue());
    assertThat(indicesStatsResponse.getIndex(index3), notNullValue());
}
项目:Android-Scrapper    文件:GridDialogItemFragment.java   
private void setTexts() {
    dateTime.setText(
            DateTimeFormat.forPattern("MMM dd  hh:mm aa").print(new DateTime(game.getGameDateTime(), Constants.DATE.VEGAS_TIME_ZONE).toDateTime(DateTimeZone.getDefault())));
    if (game.getFirstTeam().getName().equals(DefaultFactory.Team.NAME)) {
        firstTeamTitle.setText(game.getFirstTeam().getCity());
        firstTeamSubtitle.setText("-");
    } else {
        firstTeamTitle.setText(game.getFirstTeam().getName() + " " + String.valueOf(game.getFirstTeamScore()));
        firstTeamSubtitle.setText(game.getFirstTeam().getCity());
    }
    if (game.getSecondTeam().getName().equals(DefaultFactory.Team.NAME)) {
        secondTeamTitle.setText(game.getSecondTeam().getCity());
        secondTeamSubtitle.setText("-");
    } else {
        secondTeamTitle.setText(game.getSecondTeam().getName() + " " + String.valueOf(game.getSecondTeamScore()));
        secondTeamSubtitle.setText(game.getSecondTeam().getCity());
    }
    bidAmount.setText(getContext().getString(R.string.bid_amount,
            game.getLeagueType() instanceof Soccer_Spread ? "(" + (int) game.getVIBid().getVigAmount() + ") " : game.getVIBid().getCondition().getValue().replace("spread", ""),
            String.valueOf(game.getVIBid().getBidAmount())));
}
项目:device-telemetry-java    文件:RuleServiceModel.java   
public RuleServiceModel(
    final String eTag,
    final String id,
    final String name,
    final String dateCreated,
    final Boolean enabled,
    final String description,
    final String groupId,
    final String severity,
    final ArrayList<ConditionServiceModel> conditions) {

    this.eTag = eTag;
    this.id = id;
    this.name = name;
    this.dateCreated = dateCreated;
    this.dateModified = DateTime.now(DateTimeZone.UTC).toString(DATE_FORMAT);
    this.enabled = enabled;
    this.description = description;
    this.groupId = groupId;
    this.severity = severity;

    this.conditions = conditions;
}
项目:elasticsearch_my    文件:DateHistogramIT.java   
public void testSingleValuedFieldOrderedBySubAggregationAsc() throws Exception {
    SearchResponse response = client().prepareSearch("idx")
            .addAggregation(dateHistogram("histo")
                    .field("date")
                    .dateHistogramInterval(DateHistogramInterval.MONTH)
                    .order(Histogram.Order.aggregation("sum", true))
                    .subAggregation(max("sum").field("value")))
            .execute().actionGet();

    assertSearchResponse(response);

    Histogram histo = response.getAggregations().get("histo");
    assertThat(histo, notNullValue());
    assertThat(histo.getName(), equalTo("histo"));
    assertThat(histo.getBuckets().size(), equalTo(3));

    int i = 0;
    for (Histogram.Bucket bucket : histo.getBuckets()) {
        assertThat(((DateTime) bucket.getKey()), equalTo(new DateTime(2012, i + 1, 1, 0, 0, DateTimeZone.UTC)));
        i++;
    }
}
项目:alfresco-repository    文件:TikaPoweredMetadataExtracter.java   
public TikaPoweredMetadataExtracter(String extractorContext, HashSet<String> supportedMimeTypes, HashSet<String> supportedEmbedMimeTypes)
{
    super(supportedMimeTypes, supportedEmbedMimeTypes);

    this.extractorContext = extractorContext;

    // TODO Once TIKA-451 is fixed this list will get nicer
    DateTimeParser[] parsersUTC = {
        DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss'Z'").getParser(),
        DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ").getParser()
    };
    DateTimeParser[] parsers = {
        DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss").getParser(),
        DateTimeFormat.forPattern("yyyy-MM-dd").getParser(),
        DateTimeFormat.forPattern("yyyy/MM/dd HH:mm:ss").getParser(),
        DateTimeFormat.forPattern("yyyy/MM/dd").getParser(),
            DateTimeFormat.forPattern("EEE MMM dd hh:mm:ss zzz yyyy").getParser()
    };

    this.tikaUTCDateFormater = new DateTimeFormatterBuilder().append(null, parsersUTC).toFormatter().withZone(DateTimeZone.UTC);
    this.tikaDateFormater = new DateTimeFormatterBuilder().append(null, parsers).toFormatter();
}
项目:elasticsearch_my    文件:DateHistogramIT.java   
public void testSingleValuedFieldOrderedByMultiValuedSubAggregationDesc() throws Exception {
    SearchResponse response = client().prepareSearch("idx")
            .addAggregation(dateHistogram("histo")
                    .field("date")
                    .dateHistogramInterval(DateHistogramInterval.MONTH)
                    .order(Histogram.Order.aggregation("stats", "sum", false))
                    .subAggregation(stats("stats").field("value")))
            .execute().actionGet();

    assertSearchResponse(response);

    Histogram histo = response.getAggregations().get("histo");
    assertThat(histo, notNullValue());
    assertThat(histo.getName(), equalTo("histo"));
    assertThat(histo.getBuckets().size(), equalTo(3));

    int i = 2;
    for (Histogram.Bucket bucket : histo.getBuckets()) {
        assertThat(((DateTime) bucket.getKey()), equalTo(new DateTime(2012, i + 1, 1, 0, 0, DateTimeZone.UTC)));
        i--;
    }
}
项目:kafka-connect-hdfs    文件:HourlyPartitioner.java   
@Override
public void configure(Map<String, Object> config) {
  String localeString = (String) config.get(HdfsSinkConnectorConfig.LOCALE_CONFIG);
  if (localeString.equals("")) {
    throw new ConfigException(HdfsSinkConnectorConfig.LOCALE_CONFIG,
                              localeString, "Locale cannot be empty.");
  }
  String timeZoneString = (String) config.get(HdfsSinkConnectorConfig.TIMEZONE_CONFIG);
  if (timeZoneString.equals("")) {
    throw new ConfigException(HdfsSinkConnectorConfig.TIMEZONE_CONFIG,
                              timeZoneString, "Timezone cannot be empty.");
  }
  String hiveIntString = (String) config.get(HdfsSinkConnectorConfig.HIVE_INTEGRATION_CONFIG);
  boolean hiveIntegration = hiveIntString != null && hiveIntString.toLowerCase().equals("true");
  Locale locale = new Locale(localeString);
  DateTimeZone timeZone = DateTimeZone.forID(timeZoneString);
  init(partitionDurationMs, pathFormat, locale, timeZone, hiveIntegration);
}
项目:alfresco-repository    文件:ImporterComponentTest.java   
@Override
protected void onSetUpInTransaction() throws Exception
{
    nodeService = (NodeService)applicationContext.getBean(ServiceRegistry.NODE_SERVICE.getLocalName());
    importerService = (ImporterService)applicationContext.getBean(ServiceRegistry.IMPORTER_SERVICE.getLocalName());

    importerBootstrap = (ImporterBootstrap)applicationContext.getBean("spacesBootstrap");

    this.authenticationComponent = (AuthenticationComponent)this.applicationContext.getBean("authenticationComponent");

    this.authenticationComponent.setSystemUserAsCurrentUser();

    this.versionService = (VersionService)this.applicationContext.getBean("VersionService");

    // Create the store
    this.storeRef = nodeService.createStore(StoreRef.PROTOCOL_WORKSPACE, "Test_" + System.currentTimeMillis());

    TimeZone tz = TimeZone.getTimeZone("GMT");
    TimeZone.setDefault(tz);
    // Joda time has already grabbed the JVM zone so re-set it here
    DateTimeZone.setDefault(DateTimeZone.forTimeZone(tz));
}
项目:elasticsearch_my    文件:TimeZoneRoundingTests.java   
/**
 * Randomized test on TimeUnitRounding. Test uses random
 * {@link DateTimeUnit} and {@link DateTimeZone} and often (50% of the time)
 * chooses test dates that are exactly on or close to offset changes (e.g.
 * DST) in the chosen time zone.
 *
 * It rounds the test date down and up and performs various checks on the
 * rounding unit interval that is defined by this. Assumptions tested are
 * described in
 * {@link #assertInterval(long, long, long, Rounding, DateTimeZone)}
 */
public void testRoundingRandom() {
    for (int i = 0; i < 1000; ++i) {
        DateTimeUnit timeUnit = randomTimeUnit();
        DateTimeZone tz = randomDateTimeZone();
        Rounding rounding = new Rounding.TimeUnitRounding(timeUnit, tz);
        long date = Math.abs(randomLong() % (2 * (long) 10e11)); // 1970-01-01T00:00:00Z - 2033-05-18T05:33:20.000+02:00
        long unitMillis = timeUnit.field(tz).getDurationField().getUnitMillis();
        if (randomBoolean()) {
            nastyDate(date, tz, unitMillis);
        }
        final long roundedDate = rounding.round(date);
        final long nextRoundingValue = rounding.nextRoundingValue(roundedDate);

        assertInterval(roundedDate, date, nextRoundingValue, rounding, tz);

        // check correct unit interval width for units smaller than a day, they should be fixed size except for transitions
        if (unitMillis <= DateTimeConstants.MILLIS_PER_DAY) {
            // if the interval defined didn't cross timezone offset transition, it should cover unitMillis width
            if (tz.getOffset(roundedDate - 1) == tz.getOffset(nextRoundingValue + 1)) {
                assertThat("unit interval width not as expected for [" + timeUnit + "], [" + tz + "] at "
                        + new DateTime(roundedDate), nextRoundingValue - roundedDate, equalTo(unitMillis));
            }
        }
    }
}
项目:autorest.java    文件:PolymorphismTests.java   
@Test
public void getValid() throws Exception {
    Fish result = client.polymorphisms().getValid();
    Assert.assertEquals(Salmon.class, result.getClass());
    Salmon salmon = (Salmon) result;
    Assert.assertEquals("alaska", salmon.location());
    Assert.assertEquals(1.0, salmon.length(), 0f);
    Assert.assertEquals(3, salmon.siblings().size());
    Assert.assertEquals(Shark.class, salmon.siblings().get(0).getClass());
    Shark sib1 = (Shark) (salmon.siblings().get(0));
    Assert.assertEquals(new DateTime(2012, 1, 5, 1, 0, 0, DateTimeZone.UTC), sib1.birthday());
    Assert.assertEquals(Sawshark.class, salmon.siblings().get(1).getClass());
    Sawshark sib2 = (Sawshark) (salmon.siblings().get(1));
    Assert.assertArrayEquals(
            new byte[]{(byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 254},
            sib2.picture());
    Goblinshark sib3 = (Goblinshark) (salmon.siblings().get(2));
    Assert.assertEquals(1, sib3.age().longValue());
    Assert.assertEquals(5, sib3.jawsize().longValue());
}
项目:googlecloud-techtalk    文件:DateTimeToStringTest.java   
@Test
public void shouldTransform() {
    assertThat(transformer.from(new DateTime(2014, 6, 1, 12, 34, 56, 123).withZoneRetainFields(DateTimeZone.forOffsetHours(10))), is("2014-06-01T12:34:56.123+10:00"));
    assertThat(transformer.from(new DateTime(2014, 6, 1, 12, 34, 56, 123).withZoneRetainFields(DateTimeZone.forOffsetHours(-10))), is("2014-06-01T12:34:56.123-10:00"));
    assertThat(transformer.from(new DateTime(2014, 6, 1, 12, 34, 56, 123).withZoneRetainFields(DateTimeZone.forOffsetHoursMinutes(10, 30))), is("2014-06-01T12:34:56.123+10:30"));
    assertThat(transformer.from(new DateTime(2014, 6, 1, 12, 34, 56, 123).withZoneRetainFields(DateTimeZone.forOffsetHours(0))), is("2014-06-01T12:34:56.123Z"));
    assertThat(transformer.from(new DateTime(2014, 6, 1, 12, 34, 56, 123).withZoneRetainFields(DateTimeZone.UTC)), is("2014-06-01T12:34:56.123Z"));
    assertThat(transformer.from(new DateTime(2014, 6, 1, 12, 34, 56).withZoneRetainFields(DateTimeZone.UTC)), is("2014-06-01T12:34:56.000Z"));
    assertThat(transformer.from(new DateTime(2014, 6, 1, 12, 34, 0).withZoneRetainFields(DateTimeZone.UTC)), is("2014-06-01T12:34:00.000Z"));
    assertThat(transformer.from(new DateTime(2014, 6, 1, 12, 0, 0).withZoneRetainFields(DateTimeZone.UTC)), is("2014-06-01T12:00:00.000Z"));
    assertThat(transformer.from(new DateTime(2014, 6, 1, 0, 0, 0).withZoneRetainFields(DateTimeZone.UTC)), is("2014-06-01T00:00:00.000Z"));
    assertThat(transformer.from(new DateTime(2014, 6, 1, 0, 0, 0).withZoneRetainFields(DateTimeZone.UTC)), is("2014-06-01T00:00:00.000Z"));
    assertThat(transformer.from(new DateTime(2014, 1, 1, 0, 0, 0).withZoneRetainFields(DateTimeZone.UTC)), is("2014-01-01T00:00:00.000Z"));
    assertThat(transformer.from(new DateTime(2014, 6, 1, 12, 34, 56).withZoneRetainFields(DateTimeZone.forOffsetHours(8))), is("2014-06-01T12:34:56.000+08:00"));
    assertThat(transformer.from(new DateTime(2014, 6, 1, 12, 34, 0).withZoneRetainFields(DateTimeZone.forOffsetHours(8))), is("2014-06-01T12:34:00.000+08:00"));
    assertThat(transformer.from(new DateTime(2014, 6, 1, 12, 0, 0).withZoneRetainFields(DateTimeZone.forOffsetHours(8))), is("2014-06-01T12:00:00.000+08:00"));
}
项目:unitimes    文件:ServerTimeZoneBackend.java   
@Override
public ServerTimeZoneResponse execute(ServerTimeZoneRequest request, SessionContext context) {
    Date first = null, last = null;
    for (Session session: SessionDAO.getInstance().findAll()) {
        if (first == null || first.after(session.getEventBeginDate()))
            first = session.getEventBeginDate();
        if (last == null || last.before(session.getEventEndDate()))
            last = session.getEventEndDate();
    }
    DateTimeZone zone = DateTimeZone.getDefault();
    int offsetInMinutes = zone.getOffset(first.getTime()) / 60000;
    ServerTimeZoneResponse ret = new ServerTimeZoneResponse();
    ret.setId(zone.getID());
    ret.addName(zone.getName(new Date().getTime()));
    ret.setTimeZoneOffsetInMinutes(offsetInMinutes);
    long time = first.getTime();
    long transition;
    while (time != (transition = zone.nextTransition(time)) && time < last.getTime()) {
        int adjustment = (zone.getOffset(transition) / 60000) - offsetInMinutes;
        ret.addTransition((int)(transition / 3600000), adjustment);
        time = transition;
    }
    return ret;
}
项目:elasticsearch_my    文件:RangeFieldMapper.java   
@Override
public Query rangeQuery(String field, Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper,
                        ShapeRelation relation, @Nullable DateTimeZone timeZone, @Nullable DateMathParser parser,
                        QueryShardContext context) {
    DateTimeZone zone = (timeZone == null) ? DateTimeZone.UTC : timeZone;
    DateMathParser dateMathParser = (parser == null) ?
        new DateMathParser(DateFieldMapper.DEFAULT_DATE_TIME_FORMATTER) : parser;
    Long low = lowerTerm == null ? Long.MIN_VALUE :
        dateMathParser.parse(lowerTerm instanceof BytesRef ? ((BytesRef) lowerTerm).utf8ToString() : lowerTerm.toString(),
            context::nowInMillis, false, zone);
    Long high = upperTerm == null ? Long.MAX_VALUE :
        dateMathParser.parse(upperTerm instanceof BytesRef ? ((BytesRef) upperTerm).utf8ToString() : upperTerm.toString(),
            context::nowInMillis, false, zone);

    return super.rangeQuery(field, low, high, includeLower, includeUpper, relation, zone, dateMathParser, context);
}
项目:autorest.java    文件:IntsImpl.java   
/**
 * Put datetime encoded as Unix time.
 *
 * @param intBody the long value
 * @throws IllegalArgumentException thrown if parameters fail the validation
 * @return the {@link ServiceResponse} object if successful.
 */
public Observable<ServiceResponse<Void>> putUnixTimeDateWithServiceResponseAsync(DateTime intBody) {
    Long intBodyConverted = intBody.toDateTime(DateTimeZone.UTC).getMillis() / 1000;
    return service.putUnixTimeDate(intBodyConverted)
        .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Void>>>() {
            @Override
            public Observable<ServiceResponse<Void>> call(Response<ResponseBody> response) {
                try {
                    ServiceResponse<Void> clientResponse = putUnixTimeDateDelegate(response);
                    return Observable.just(clientResponse);
                } catch (Throwable t) {
                    return Observable.error(t);
                }
            }
        });
}
项目:elasticsearch_my    文件:SimpleJodaTests.java   
public void testMultiParsers() {
    DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder();
    DateTimeParser[] parsers = new DateTimeParser[3];
    parsers[0] = DateTimeFormat.forPattern("MM/dd/yyyy").withZone(DateTimeZone.UTC).getParser();
    parsers[1] = DateTimeFormat.forPattern("MM-dd-yyyy").withZone(DateTimeZone.UTC).getParser();
    parsers[2] = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").withZone(DateTimeZone.UTC).getParser();
    builder.append(DateTimeFormat.forPattern("MM/dd/yyyy").withZone(DateTimeZone.UTC).getPrinter(), parsers);

    DateTimeFormatter formatter = builder.toFormatter();

    formatter.parseMillis("2009-11-15 14:12:12");
}
项目:elasticsearch_my    文件:DateDerivativeIT.java   
/**
 * Do a derivative on a date histogram with time zone CET at DST start
 */
public void testSingleValuedFieldNormalised_timeZone_CET_DstStart() throws Exception {
    createIndex(IDX_DST_START);
    List<IndexRequestBuilder> builders = new ArrayList<>();

    DateTimeZone timezone = DateTimeZone.forID("CET");
    addNTimes(1, IDX_DST_START, new DateTime("2012-03-24T01:00:00", timezone), builders);
    addNTimes(2, IDX_DST_START, new DateTime("2012-03-25T01:00:00", timezone), builders); // day with dst shift, only 23h long
    addNTimes(3, IDX_DST_START, new DateTime("2012-03-26T01:00:00", timezone), builders);
    addNTimes(4, IDX_DST_START, new DateTime("2012-03-27T01:00:00", timezone), builders);
    indexRandom(true, builders);
    ensureSearchable();

    SearchResponse response = client()
            .prepareSearch(IDX_DST_START)
            .addAggregation(dateHistogram("histo").field("date").dateHistogramInterval(DateHistogramInterval.DAY)
                    .timeZone(timezone).minDocCount(0)
                    .subAggregation(derivative("deriv", "_count").unit(DateHistogramInterval.HOUR)))
            .execute()
            .actionGet();

    assertSearchResponse(response);

    Histogram deriv = response.getAggregations().get("histo");
    assertThat(deriv, notNullValue());
    assertThat(deriv.getName(), equalTo("histo"));
    List<? extends Bucket> buckets = deriv.getBuckets();
    assertThat(buckets.size(), equalTo(4));

    assertBucket(buckets.get(0), new DateTime("2012-03-24", timezone).toDateTime(DateTimeZone.UTC), 1L, nullValue(), null, null);
    assertBucket(buckets.get(1), new DateTime("2012-03-25", timezone).toDateTime(DateTimeZone.UTC), 2L, notNullValue(), 1d, 1d / 24d);
    // the following is normalized using a 23h bucket width
    assertBucket(buckets.get(2), new DateTime("2012-03-26", timezone).toDateTime(DateTimeZone.UTC), 3L, notNullValue(), 1d, 1d / 23d);
    assertBucket(buckets.get(3), new DateTime("2012-03-27", timezone).toDateTime(DateTimeZone.UTC), 4L, notNullValue(), 1d, 1d / 24d);
}
项目:elasticsearch_my    文件:DateHistogramIT.java   
public void testSingleValued_timeZone_epoch() throws Exception {
    String format = randomBoolean() ? "epoch_millis" : "epoch_second";
    int millisDivider = format.equals("epoch_millis") ? 1 : 1000;
    if (randomBoolean()) {
        format = format + "||date_optional_time";
    }
    DateTimeZone tz = DateTimeZone.forID("+01:00");
    SearchResponse response = client().prepareSearch("idx")
            .addAggregation(dateHistogram("histo").field("date")
                    .dateHistogramInterval(DateHistogramInterval.DAY).minDocCount(1)
                    .timeZone(tz).format(format))
            .execute()
            .actionGet();
    assertSearchResponse(response);

    Histogram histo = response.getAggregations().get("histo");
    assertThat(histo, notNullValue());
    assertThat(histo.getName(), equalTo("histo"));
    List<? extends Bucket> buckets = histo.getBuckets();
    assertThat(buckets.size(), equalTo(6));

    List<DateTime> expectedKeys = new ArrayList<>();
    expectedKeys.add(new DateTime(2012, 1, 1, 23, 0, DateTimeZone.UTC));
    expectedKeys.add(new DateTime(2012, 2, 1, 23, 0, DateTimeZone.UTC));
    expectedKeys.add(new DateTime(2012, 2, 14, 23, 0, DateTimeZone.UTC));
    expectedKeys.add(new DateTime(2012, 3, 1, 23, 0, DateTimeZone.UTC));
    expectedKeys.add(new DateTime(2012, 3, 14, 23, 0, DateTimeZone.UTC));
    expectedKeys.add(new DateTime(2012, 3, 22, 23, 0, DateTimeZone.UTC));


    Iterator<DateTime> keyIterator = expectedKeys.iterator();
    for (Histogram.Bucket bucket : buckets) {
        assertThat(bucket, notNullValue());
        DateTime expectedKey = keyIterator.next();
        assertThat(bucket.getKeyAsString(), equalTo(Long.toString(expectedKey.getMillis() / millisDivider)));
        assertThat(((DateTime) bucket.getKey()), equalTo(expectedKey));
        assertThat(bucket.getDocCount(), equalTo(1L));
    }
}
项目:springboot-spwa-gae-demo    文件:StringToDateTimeTest.java   
@Test
public void shouldTransformLeniently() {
    assertThat(transformer.from("2014-06-01T12:34:56.12").compareTo(new DateTime(2014, 6, 1, 12, 34, 56, 120)), is(0));
    assertThat(transformer.from("2014-06-01T12:34:56.1").compareTo(new DateTime(2014, 6, 1, 12, 34, 56, 100)), is(0));
    assertThat(transformer.from("2014-06-01T12:34:56").compareTo(new DateTime(2014, 6, 1, 12, 34, 56)), is(0));
    assertThat(transformer.from("2014-06-01T12:34").compareTo(new DateTime(2014, 6, 1, 12, 34, 0)), is(0));
    assertThat(transformer.from("2014-06-01T12").compareTo(new DateTime(2014, 6, 1, 12, 0, 0)), is(0));
    assertThat(transformer.from("2014-06-01").compareTo(new DateTime(2014, 6, 1, 0, 0, 0)), is(0));
    assertThat(transformer.from("2014-06").compareTo(new DateTime(2014, 6, 1, 0, 0, 0)), is(0));
    assertThat(transformer.from("2014").compareTo(new DateTime(2014, 1, 1, 0, 0, 0)), is(0));
    assertThat(transformer.from("2014-06-01T12:34:56+08:00").compareTo(new DateTime(2014, 6, 1, 12, 34, 56).withZoneRetainFields(DateTimeZone.forOffsetHours(8))), is(0));
    assertThat(transformer.from("2014-06-01T12:34+08:00").compareTo(new DateTime(2014, 6, 1, 12, 34, 0).withZoneRetainFields(DateTimeZone.forOffsetHours(8))), is(0));
    assertThat(transformer.from("2014-06-01T12+08:00").compareTo(new DateTime(2014, 6, 1, 12, 0, 0).withZoneRetainFields(DateTimeZone.forOffsetHours(8))), is(0));
}
项目:tableschema-java    文件:FieldTest.java   
@Test
public void testFieldCastDateTime() throws Exception{   
    Field field = new Field("test", Field.FIELD_TYPE_DATETIME); 
    DateTime val = field.castValue("2008-08-30T01:45:36.123Z");

    Assert.assertEquals(2008, val.withZone(DateTimeZone.UTC).getYear());
    Assert.assertEquals(8, val.withZone(DateTimeZone.UTC).getMonthOfYear());
    Assert.assertEquals(30, val.withZone(DateTimeZone.UTC).getDayOfMonth());
    Assert.assertEquals(1, val.withZone(DateTimeZone.UTC).getHourOfDay());
    Assert.assertEquals(45, val.withZone(DateTimeZone.UTC).getMinuteOfHour());
    Assert.assertEquals("2008-08-30T01:45:36.123Z", val.withZone(DateTimeZone.UTC).toString());
}
项目:springboot-shiro-cas-mybatis    文件:WsFederationCredentialTests.java   
@Test
public void verifyIsValidOldToken() throws Exception {
    standardCred.setNotBefore(new DateTime().withZone(DateTimeZone.UTC).minusDays(1));
    standardCred.setNotOnOrAfter(new DateTime().withZone(DateTimeZone.UTC).plusHours(1).minusDays(1));
    standardCred.setIssuedOn(new DateTime().withZone(DateTimeZone.UTC).minusDays(1));

    final boolean result = standardCred.isValid("urn:federation:cas", "http://adfs.example.com/adfs/services/trust", 2000);
    assertFalse("testIsValidOldToken() - False", result);
}
项目:AppleSeed    文件:StringToDateTest.java   
@Test
public void shouldTransformLeniently() {
    assertThat(transformer.from("2014-06-01T12:34:56"), is(new DateTime(2014, 6, 1, 12, 34, 56).toDate()));
    assertThat(transformer.from("2014-06-01T12:34"), is(new DateTime(2014, 6, 1, 12, 34, 0).toDate()));
    assertThat(transformer.from("2014-06-01T12"), is(new DateTime(2014, 6, 1, 12, 0, 0).toDate()));
    assertThat(transformer.from("2014-06-01"), is(new DateTime(2014, 6, 1, 0, 0, 0).toDate()));
    assertThat(transformer.from("2014-06"), is(new DateTime(2014, 6, 1, 0, 0, 0).toDate()));
    assertThat(transformer.from("2014"), is(new DateTime(2014, 1, 1, 0, 0, 0).toDate()));
    assertThat(transformer.from("2014-06-01T12:34:56+08:00"), is(new DateTime(2014, 6, 1, 12, 34, 56).withZoneRetainFields(DateTimeZone.forOffsetHours(8)).toDate()));
    assertThat(transformer.from("2014-06-01T12:34+08:00"), is(new DateTime(2014, 6, 1, 12, 34, 0).withZoneRetainFields(DateTimeZone.forOffsetHours(8)).toDate()));
    assertThat(transformer.from("2014-06-01T12+08:00"), is(new DateTime(2014, 6, 1, 12, 0, 0).withZoneRetainFields(DateTimeZone.forOffsetHours(8)).toDate()));
}
项目:Elasticsearch    文件:TimeZoneParser.java   
public static DateTimeZone parseTimeZone(BytesRef timezone) throws IllegalArgumentException {
    if (timezone == null) {
        throw new IllegalArgumentException("invalid time zone value NULL");
    }
    if (timezone.equals(DEFAULT_TZ_BYTES_REF)) {
        return DEFAULT_TZ;
    }

    DateTimeZone tz = TIME_ZONE_MAP.get(timezone);
    if (tz == null) {
        try {
            String text = timezone.utf8ToString();
            int index = text.indexOf(':');
            if (index != -1) {
                int beginIndex = text.charAt(0) == '+' ? 1 : 0;
                // format like -02:30
                tz = DateTimeZone.forOffsetHoursMinutes(
                        Integer.parseInt(text.substring(beginIndex, index)),
                        Integer.parseInt(text.substring(index + 1))
                );
            } else {
                // id, listed here: http://joda-time.sourceforge.net/timezones.html
                // or here: http://www.joda.org/joda-time/timezones.html
                tz = DateTimeZone.forID(text);
            }
        } catch (IllegalArgumentException e) {
            throw new IllegalArgumentException(String.format(Locale.ENGLISH,
                    "invalid time zone value '%s'", timezone.utf8ToString()));
        }
        TIME_ZONE_MAP.putIfAbsent(timezone, tz);
    }
    return tz;
}
项目:exam    文件:ExamRoom.java   
@Transient
public List<OpeningHours> getWorkingHoursForDate(LocalDate date) {
    List<OpeningHours> workingHours = getDefaultWorkingHours(date);
    List<Interval> extensionEvents = DateTimeUtils.mergeSlots(
            DateTimeUtils.getExceptionEvents(calendarExceptionEvents, date, DateTimeUtils.RestrictionType.NON_RESTRICTIVE));
    List<Interval> restrictionEvents = DateTimeUtils.mergeSlots(
            DateTimeUtils.getExceptionEvents(calendarExceptionEvents, date, DateTimeUtils.RestrictionType.RESTRICTIVE));
    List<OpeningHours> availableHours = new ArrayList<>();
    if (!extensionEvents.isEmpty()) {
        List<Interval> unifiedIntervals = new ArrayList<>();
        for (OpeningHours oh : workingHours) {
            unifiedIntervals.add(oh.getHours());
        }
        unifiedIntervals.addAll(extensionEvents);
        unifiedIntervals = DateTimeUtils.mergeSlots(unifiedIntervals);
        int tzOffset;
        if (workingHours.isEmpty()) {
            tzOffset = DateTimeZone.forID(localTimezone).getOffset(new DateTime(date));
        } else {
            tzOffset = workingHours.get(0).timezoneOffset;
        }
        workingHours.clear();
        workingHours.addAll(unifiedIntervals.stream().map(
                interval -> new OpeningHours(interval, tzOffset)).collect(Collectors.toList()));
    }
    if (!restrictionEvents.isEmpty()) {
        for (OpeningHours hours : workingHours) {
            Interval slot = hours.getHours();
            for (Interval gap : DateTimeUtils.findGaps(restrictionEvents, slot)) {
                availableHours.add(new OpeningHours(gap, hours.getTimezoneOffset()));
            }
        }
    } else {
        availableHours = workingHours;
    }
    return availableHours;
}
项目:elasticsearch_my    文件:TimeZoneRoundingTests.java   
public void testTimeUnitRoundingDST() {
    Rounding tzRounding;
    // testing savings to non savings switch
    DateTimeZone cet = DateTimeZone.forID("CET");
    tzRounding = Rounding.builder(DateTimeUnit.HOUR_OF_DAY).timeZone(cet).build();
    assertThat(tzRounding.round(time("2014-10-26T01:01:01", cet)), isDate(time("2014-10-26T01:00:00+02:00"), cet));
    assertThat(tzRounding.nextRoundingValue(time("2014-10-26T01:00:00", cet)),isDate(time("2014-10-26T02:00:00+02:00"), cet));
    assertThat(tzRounding.nextRoundingValue(time("2014-10-26T02:00:00", cet)), isDate(time("2014-10-26T02:00:00+01:00"), cet));

    // testing non savings to savings switch
    tzRounding = Rounding.builder(DateTimeUnit.HOUR_OF_DAY).timeZone(cet).build();
    assertThat(tzRounding.round(time("2014-03-30T01:01:01", cet)), isDate(time("2014-03-30T01:00:00+01:00"), cet));
    assertThat(tzRounding.nextRoundingValue(time("2014-03-30T01:00:00", cet)), isDate(time("2014-03-30T03:00:00", cet), cet));
    assertThat(tzRounding.nextRoundingValue(time("2014-03-30T03:00:00", cet)), isDate(time("2014-03-30T04:00:00", cet), cet));

    // testing non savings to savings switch (America/Chicago)
    DateTimeZone chg = DateTimeZone.forID("America/Chicago");
    Rounding tzRounding_utc = Rounding.builder(DateTimeUnit.HOUR_OF_DAY).timeZone(DateTimeZone.UTC).build();
    assertThat(tzRounding.round(time("2014-03-09T03:01:01", chg)), isDate(time("2014-03-09T03:00:00", chg), chg));

    Rounding tzRounding_chg = Rounding.builder(DateTimeUnit.HOUR_OF_DAY).timeZone(chg).build();
    assertThat(tzRounding_chg.round(time("2014-03-09T03:01:01", chg)), isDate(time("2014-03-09T03:00:00", chg), chg));

    // testing savings to non savings switch 2013 (America/Chicago)
    assertThat(tzRounding_utc.round(time("2013-11-03T06:01:01", chg)), isDate(time("2013-11-03T06:00:00", chg), chg));
    assertThat(tzRounding_chg.round(time("2013-11-03T06:01:01", chg)), isDate(time("2013-11-03T06:00:00", chg), chg));

    // testing savings to non savings switch 2014 (America/Chicago)
    assertThat(tzRounding_utc.round(time("2014-11-02T06:01:01", chg)), isDate(time("2014-11-02T06:00:00", chg), chg));
    assertThat(tzRounding_chg.round(time("2014-11-02T06:01:01", chg)), isDate(time("2014-11-02T06:00:00", chg), chg));
}
项目:device-telemetry-java    文件:MessageServiceModel.java   
public MessageServiceModel(
    final String deviceId,
    final long time,
    final JsonNode data) {

    this.deviceId = deviceId;
    this.time = new DateTime(time, DateTimeZone.UTC);
    this.data = data;
}
项目:device-telemetry-java    文件:AlarmServiceModel.java   
public AlarmServiceModel(Document doc) {
    if (doc != null) {
        this.eTag = doc.getETag();
        this.id = doc.getId();
        this.dateCreated = new DateTime(doc.getLong("created"), DateTimeZone.UTC);
        this.dateModified = new DateTime(doc.getLong("modified"), DateTimeZone.UTC);
        this.description = doc.getString("description");
        this.groupId = doc.getString("group.id");
        this.deviceId = doc.getString("device.id");
        this.status = doc.getString("status");
        this.ruleId = doc.getString("rule.id");
        this.ruleSeverity = doc.getString("rule.severity");
        this.ruleDescription = doc.getString("rule.description");
    } else {
        this.eTag = null;
        this.id = null;
        this.dateCreated = null;
        this.dateModified = null;
        this.description = null;
        this.groupId = null;
        this.deviceId = null;
        this.status = null;
        this.ruleId = null;
        this.ruleSeverity = null;
        this.ruleDescription = null;
    }
}
项目:cas-server-4.2.1    文件:WsFederationHelper.java   
/**
 * createCredentialFromToken converts a SAML 1.1 assertion to a WSFederationCredential.
 *
 * @param assertion the provided assertion
 * @return an equivalent credential.
 */
public WsFederationCredential createCredentialFromToken(final Assertion assertion) {
    final DateTime retrievedOn = new DateTime().withZone(DateTimeZone.UTC);
    LOGGER.debug("Retrieved on {}", retrievedOn);

    final WsFederationCredential credential = new WsFederationCredential();
    credential.setRetrievedOn(retrievedOn);
    credential.setId(assertion.getID());
    credential.setIssuer(assertion.getIssuer());
    credential.setIssuedOn(assertion.getIssueInstant());

    final Conditions conditions = assertion.getConditions();
    if (conditions != null) {
        credential.setNotBefore(conditions.getNotBefore());
        credential.setNotOnOrAfter(conditions.getNotOnOrAfter());
        credential.setAudience(conditions.getAudienceRestrictionConditions().get(0).getAudiences().get(0).getUri());
    }

    if (!assertion.getAuthenticationStatements().isEmpty()) {
        credential.setAuthenticationMethod(assertion.getAuthenticationStatements().get(0).getAuthenticationMethod());
    }

    //retrieve an attributes from the assertion
    final HashMap<String, List<Object>> attributes = new HashMap<>();
    for (final Attribute item : assertion.getAttributeStatements().get(0).getAttributes()) {
        LOGGER.debug("Processed attribute: {}", item.getAttributeName());

        final List<Object> itemList = new ArrayList<>();
        for (int i = 0; i < item.getAttributeValues().size(); i++) {
            itemList.add(((XSAny) item.getAttributeValues().get(i)).getTextContent());
        }

        if (!itemList.isEmpty()) {
            attributes.put(item.getAttributeName(), itemList);
        }
    }
    credential.setAttributes(attributes);
    LOGGER.debug("Credential: {}", credential);
    return credential;
}
项目:elasticsearch_my    文件:DateHistogramOffsetIT.java   
/**
 * Set offset so day buckets start at 6am. Index first 12 hours for two days, with one day gap.
 */
public void testSingleValueWithOffsetMinDocCount() throws Exception {
    prepareIndex(date("2014-03-11T00:00:00+00:00"), 12, 1, 0);
    prepareIndex(date("2014-03-14T00:00:00+00:00"), 12, 1, 13);

    SearchResponse response = client().prepareSearch("idx2")
            .setQuery(matchAllQuery())
            .addAggregation(dateHistogram("date_histo")
                    .field("date")
                    .offset("6h")
                    .minDocCount(0)
                    .format(DATE_FORMAT)
                    .dateHistogramInterval(DateHistogramInterval.DAY))
            .execute().actionGet();

    assertThat(response.getHits().getTotalHits(), equalTo(24L));

    Histogram histo = response.getAggregations().get("date_histo");
    List<? extends Histogram.Bucket> buckets = histo.getBuckets();
    assertThat(buckets.size(), equalTo(5));

    checkBucketFor(buckets.get(0), new DateTime(2014, 3, 10, 6, 0, DateTimeZone.UTC), 6L);
    checkBucketFor(buckets.get(1), new DateTime(2014, 3, 11, 6, 0, DateTimeZone.UTC), 6L);
    checkBucketFor(buckets.get(2), new DateTime(2014, 3, 12, 6, 0, DateTimeZone.UTC), 0L);
    checkBucketFor(buckets.get(3), new DateTime(2014, 3, 13, 6, 0, DateTimeZone.UTC), 6L);
    checkBucketFor(buckets.get(4), new DateTime(2014, 3, 14, 6, 0, DateTimeZone.UTC), 6L);
}
项目:CalendarFX    文件:TimeZoneConverterTest.java   
private static void assertOffsetsEqualForDate(
        TimeZone utilTz, DateTimeZone jodaTz, long offset) {

    TimeZone convertedTz = TimeZoneConverter.toTimeZone(jodaTz);

    // Test that the util timezone and it's joda timezone are equivalent.
    assertEquals("offset=" + offset + " in " + utilTz.getID(),
            utilTz.getOffset(offset), convertedTz.getOffset(offset));

    // Test the complicated getOffset method.
    // We don't care which tz the output fields are in since we're not
    // concerned that the output from getOffset(...) == offset,
    // just that the utilTz.getOffset(...) == jodaTz.getOffset(...) computed
    // from it are equal for both timezones.
    GregorianCalendar c = new GregorianCalendar();
    c.setTime(new Date(offset));
    assertEquals("offset=" + offset + " in " + utilTz.getID(),
            utilTz.getOffset(
                    c.get(Calendar.ERA),
                    c.get(Calendar.YEAR),
                    c.get(Calendar.MONTH),
                    c.get(Calendar.DAY_OF_MONTH),
                    c.get(Calendar.DAY_OF_WEEK),
                    (int) (offset % MILLIS_PER_DAY)),
            convertedTz.getOffset(
                    c.get(Calendar.ERA),
                    c.get(Calendar.YEAR),
                    c.get(Calendar.MONTH),
                    c.get(Calendar.DAY_OF_MONTH),
                    c.get(Calendar.DAY_OF_WEEK),
                    (int) (offset % MILLIS_PER_DAY)));
}
项目:cas-server-4.2.1    文件:WsFederationCredentialTests.java   
@Before
public void setUp() {
    standardCred = new WsFederationCredential();
    standardCred.setNotBefore(new DateTime().withZone(DateTimeZone.UTC));
    standardCred.setNotOnOrAfter(new DateTime().withZone(DateTimeZone.UTC).plusHours(1));
    standardCred.setIssuedOn(new DateTime().withZone(DateTimeZone.UTC));
    standardCred.setIssuer("http://adfs.example.com/adfs/services/trust");
    standardCred.setAudience("urn:federation:cas");
    standardCred.setId("_6257b2bf-7361-4081-ae1f-ec58d4310f61");
    standardCred.setRetrievedOn(new DateTime().withZone(DateTimeZone.UTC).plusSeconds(1));
}
项目:elasticsearch_my    文件:TimeZoneRoundingTests.java   
/**
 * test for #10025, strict local to UTC conversion can cause joda exceptions
 * on DST start
 */
public void testLenientConversionDST() {
    DateTimeZone tz = DateTimeZone.forID("America/Sao_Paulo");
    long start = time("2014-10-18T20:50:00.000", tz);
    long end = time("2014-10-19T01:00:00.000", tz);
    Rounding tzRounding = new Rounding.TimeUnitRounding(DateTimeUnit.MINUTES_OF_HOUR, tz);
    Rounding dayTzRounding = new Rounding.TimeIntervalRounding(60000, tz);
    for (long time = start; time < end; time = time + 60000) {
        assertThat(tzRounding.nextRoundingValue(time), greaterThan(time));
        assertThat(dayTzRounding.nextRoundingValue(time), greaterThan(time));
    }
}
项目:elasticsearch_my    文件:Joda.java   
public static FormatDateTimeFormatter getStrictStandardDateFormatter() {
    // 2014/10/10
    DateTimeFormatter shortFormatter = new DateTimeFormatterBuilder()
            .appendFixedDecimal(DateTimeFieldType.year(), 4)
            .appendLiteral('/')
            .appendFixedDecimal(DateTimeFieldType.monthOfYear(), 2)
            .appendLiteral('/')
            .appendFixedDecimal(DateTimeFieldType.dayOfMonth(), 2)
            .toFormatter()
            .withZoneUTC();

    // 2014/10/10 12:12:12
    DateTimeFormatter longFormatter = new DateTimeFormatterBuilder()
            .appendFixedDecimal(DateTimeFieldType.year(), 4)
            .appendLiteral('/')
            .appendFixedDecimal(DateTimeFieldType.monthOfYear(), 2)
            .appendLiteral('/')
            .appendFixedDecimal(DateTimeFieldType.dayOfMonth(), 2)
            .appendLiteral(' ')
            .appendFixedSignedDecimal(DateTimeFieldType.hourOfDay(), 2)
            .appendLiteral(':')
            .appendFixedSignedDecimal(DateTimeFieldType.minuteOfHour(), 2)
            .appendLiteral(':')
            .appendFixedSignedDecimal(DateTimeFieldType.secondOfMinute(), 2)
            .toFormatter()
            .withZoneUTC();

    DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder().append(longFormatter.withZone(DateTimeZone.UTC).getPrinter(), new DateTimeParser[]{longFormatter.getParser(), shortFormatter.getParser(), new EpochTimeParser(true)});

    return new FormatDateTimeFormatter("yyyy/MM/dd HH:mm:ss||yyyy/MM/dd||epoch_millis", builder.toFormatter().withZone(DateTimeZone.UTC), Locale.ROOT);
}
项目:exam    文件:CalendarController.java   
private static List<ExamStartingHour> createDefaultStartingHours(String roomTz) {
    // Get offset from Jan 1st in order to no have DST in effect
    DateTimeZone zone = DateTimeZone.forID(roomTz);
    DateTime beginning = DateTime.now().withDayOfYear(1).withTimeAtStartOfDay();
    DateTime ending = beginning.plusHours(LAST_HOUR);
    List<ExamStartingHour> hours = new ArrayList<>();
    while (!beginning.isAfter(ending)) {
        ExamStartingHour esh = new ExamStartingHour();
        esh.setStartingHour(beginning.toDate());
        esh.setTimezoneOffset(zone.getOffset(beginning));
        hours.add(esh);
        beginning = beginning.plusHours(1);
    }
    return hours;
}
项目:exam    文件:RoomController.java   
@Restrict(@Group({"ADMIN"}))
public Result updateExamRoomWorkingHours() {
    JsonNode root = request().body().asJson();
    List<Long> roomIds = new ArrayList<>();
    for (JsonNode roomId : root.get("roomIds")) {
        roomIds.add(roomId.asLong());
    }
    List<ExamRoom> rooms = Ebean.find(ExamRoom.class).where().idIn(roomIds).findList();
    List<DefaultWorkingHours> blueprints = parseWorkingHours(root);
    for (ExamRoom examRoom : rooms) {
        List<DefaultWorkingHours> previous = examRoom.getDefaultWorkingHours();
        Ebean.deleteAll(previous);
        previous.clear();
        for (DefaultWorkingHours blueprint : blueprints) {
            DefaultWorkingHours copy = new DefaultWorkingHours();
            BeanUtils.copyProperties(blueprint, copy, "id", "room");
            copy.setRoom(examRoom);
            DateTime end = new DateTime(blueprint.getEndTime());
            int offset = DateTimeZone.forID(examRoom.getLocalTimezone()).getOffset(end);
            int endMillisOfDay = DateTimeUtils.resolveEndWorkingHourMillis(end, offset) - offset;
            copy.setEndTime(end.withMillisOfDay(endMillisOfDay));
            copy.setTimezoneOffset(offset);
            copy.save();
            previous.add(copy);
        }
        asyncUpdateRemote(examRoom);
    }
    return ok();
}