org.joda.time.LocalDateTime Java Examples

The following examples show how to use org.joda.time.LocalDateTime. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TestDateTimeZone.java    From joda-time-android with Apache License 2.0 6 votes vote down vote up
@Test
public void testIsLocalDateTimeGap_Berlin() {
    DateTimeZone zone = DateTimeZone.forID("Europe/Berlin");
    assertEquals(false, zone.isLocalDateTimeGap(new LocalDateTime(2007, 3, 25, 1, 0)));
    assertEquals(false, zone.isLocalDateTimeGap(new LocalDateTime(2007, 3, 25, 1, 59, 59, 99)));
    assertEquals(true, zone.isLocalDateTimeGap(new LocalDateTime(2007, 3, 25, 2, 0)));
    assertEquals(true, zone.isLocalDateTimeGap(new LocalDateTime(2007, 3, 25, 2, 30)));
    assertEquals(true, zone.isLocalDateTimeGap(new LocalDateTime(2007, 3, 25, 2, 59, 59, 99)));
    assertEquals(false, zone.isLocalDateTimeGap(new LocalDateTime(2007, 3, 25, 3, 0)));
    assertEquals(false, zone.isLocalDateTimeGap(new LocalDateTime(2007, 3, 25, 4, 0)));
    
    assertEquals(false, zone.isLocalDateTimeGap(new LocalDateTime(2007, 10, 28, 1, 30)));  // before overlap
    assertEquals(false, zone.isLocalDateTimeGap(new LocalDateTime(2007, 10, 28, 2, 30)));  // overlap
    assertEquals(false, zone.isLocalDateTimeGap(new LocalDateTime(2007, 10, 28, 3, 30)));  // after overlap
    assertEquals(false, zone.isLocalDateTimeGap(new LocalDateTime(2007, 12, 24, 12, 34)));
}
 
Example #2
Source File: DateTimeFormatter.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Parses only the local date-time from the given text, returning a new LocalDateTime.
 * <p>
 * This will parse the text fully according to the formatter, using the UTC zone.
 * Once parsed, only the local date-time will be used.
 * This means that any parsed time-zone or offset field is completely ignored.
 * It also means that the zone and offset-parsed settings are ignored.
 *
 * @param text  the text to parse, not null
 * @return the parsed date-time, never null
 * @throws UnsupportedOperationException if parsing is not supported
 * @throws IllegalArgumentException if the text to parse is invalid
 * @since 2.0
 */
public LocalDateTime parseLocalDateTime(String text) {
    DateTimeParser parser = requireParser();
    
    Chronology chrono = selectChronology(null).withUTC();  // always use UTC, avoiding DST gaps
    DateTimeParserBucket bucket = new DateTimeParserBucket(0, chrono, iLocale, iPivotYear, iDefaultYear);
    int newPos = parser.parseInto(bucket, text, 0);
    if (newPos >= 0) {
        if (newPos >= text.length()) {
            long millis = bucket.computeMillis(true, text);
            if (bucket.getOffsetInteger() != null) {  // treat withOffsetParsed() as being true
                int parsedOffset = bucket.getOffsetInteger();
                DateTimeZone parsedZone = DateTimeZone.forOffsetMillis(parsedOffset);
                chrono = chrono.withZone(parsedZone);
            } else if (bucket.getZone() != null) {
                chrono = chrono.withZone(bucket.getZone());
            }
            return new LocalDateTime(millis, chrono);
        }
    } else {
        newPos = ~newPos;
    }
    throw new IllegalArgumentException(FormatUtils.createErrorMessage(text, newPos));
}
 
Example #3
Source File: TestNativeFunctions.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@Test
public void testDx14049() throws Exception {
  try {
    testContext.getOptions().setOption(OptionValue.createString(
      OptionValue.OptionType.SYSTEM,
      ExecConstants.QUERY_EXEC_OPTION_KEY,
      execPreferenceJava
    ));
    testFunctionsCompiledOnly(new Object[][]{
      {"months_between(c0, castDATE(c1))",new LocalDate(), new LocalDateTime(), 0.0}
    });
  } finally {
    testContext.getOptions().setOption(OptionValue.createString(
      OptionValue.OptionType.SYSTEM,
      ExecConstants.QUERY_EXEC_OPTION_KEY,
      execPreferenceGandivaOnly
    ));
  }
}
 
Example #4
Source File: TestDateTimeZone.java    From joda-time-android with Apache License 2.0 6 votes vote down vote up
@Test
public void testIsLocalDateTimeGap_NewYork() {
    DateTimeZone zone = DateTimeZone.forID("America/New_York");
    assertEquals(false, zone.isLocalDateTimeGap(new LocalDateTime(2007, 3, 11, 1, 0)));
    assertEquals(false, zone.isLocalDateTimeGap(new LocalDateTime(2007, 3, 11, 1, 59, 59, 99)));
    assertEquals(true, zone.isLocalDateTimeGap(new LocalDateTime(2007, 3, 11, 2, 0)));
    assertEquals(true, zone.isLocalDateTimeGap(new LocalDateTime(2007, 3, 11, 2, 30)));
    assertEquals(true, zone.isLocalDateTimeGap(new LocalDateTime(2007, 3, 11, 2, 59, 59, 99)));
    assertEquals(false, zone.isLocalDateTimeGap(new LocalDateTime(2007, 3, 11, 3, 0)));
    assertEquals(false, zone.isLocalDateTimeGap(new LocalDateTime(2007, 3, 11, 4, 0)));
    
    assertEquals(false, zone.isLocalDateTimeGap(new LocalDateTime(2007, 11, 4, 0, 30)));  // before overlap
    assertEquals(false, zone.isLocalDateTimeGap(new LocalDateTime(2007, 11, 4, 1, 30)));  // overlap
    assertEquals(false, zone.isLocalDateTimeGap(new LocalDateTime(2007, 11, 4, 2, 30)));  // after overlap
    assertEquals(false, zone.isLocalDateTimeGap(new LocalDateTime(2007, 12, 24, 12, 34)));
}
 
Example #5
Source File: OngoingNotificationsReceiver.java    From prayer-times-android with Apache License 2.0 6 votes vote down vote up
private Bitmap getIconFromMinutes(Times t) {
    int left = new Period(LocalDateTime.now(), t.getTime(LocalDate.now(), t.getNextTime()), PeriodType.minutes()).getMinutes();
    Resources r = getContext().getResources();

    int size = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, r.getDisplayMetrics());
    Bitmap b = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
    Canvas c = new Canvas(b);
    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    paint.setColor(0xFFFFFFFF);
    paint.setTextAlign(Paint.Align.CENTER);
    paint.setTextSize(size);
    paint.setTextSize(size * size / paint.measureText((left < 10 ? left * 10 : left) + ""));
    float yPos = c.getHeight() / 2f - (paint.descent() + paint.ascent()) / 2;
    c.drawText(left + "", size / 2f, yPos, paint);
    return b;
}
 
Example #6
Source File: TestFunctionsQuery.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@Test
@Ignore("decimal")
public void testToTimeStamp() throws Exception {
  String query = "select to_timestamp(cast('800120400.12312' as decimal(38, 5))) as DEC38_TS, to_timestamp(200120400) as INT_TS " +
      "from cp.\"employee.json\" where employee_id < 2";

  LocalDateTime result1 = new LocalDateTime(800120400123l, UTC);
  LocalDateTime result2 = new LocalDateTime(200120400000l, UTC);

  testBuilder()
      .sqlQuery(query)
      .unOrdered()
      .baselineColumns("DEC38_TS", "INT_TS")
      .baselineValues(result1, result2)
      .go();
}
 
Example #7
Source File: TestDateTimeUtils.java    From envelope with Apache License 2.0 5 votes vote down vote up
@Test
public void testParserOneFormat() {
  DateTimeParser parser = new DateTimeParser();
  parser.configureFormat(Lists.newArrayList(
      Arrays.asList("yyyy-MM-dd HH:mm:ss.SSSSS")));
  assertEquals(new LocalDateTime(parser.parse("2018-09-19 23:49:29.92284")).
      toDateTime(DateTimeZone.UTC).toString(), "2018-09-19T23:49:29.922Z");
}
 
Example #8
Source File: ResourceDAO.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
protected void create(Resource res) throws OneM2MException {
	
	Document curDoc = getDocument(URI_KEY, res.getUri());
	if (curDoc != null) {
		// added to support logic to delete expired resource
		// logic added in 2016-12-27
		String expirationTime = curDoc.getString(EXPIRETIME_KEY);
		if(expirationTime != null && Utils.checkIfExpired(expirationTime)) {
			String resUri = curDoc.getString(URI_KEY);
			this.deleteDocument(URI_KEY, resUri);
		} else {
			throw new OneM2MException(RESPONSE_STATUS.CONFLICT,
					"Resource already exist!!! :" + res.getUri());
		}
	}		

	String strJson = resourceToJson(res);
	log.debug("Res json: {} ", strJson);
	
	String currentTime = getTimeString(LocalDateTime.now());
	res.setCreationTime(currentTime);
	res.setLastModifiedTime(currentTime);

	Document doc = Document.parse(strJson);
	doc.append(ResourceDAO.URI_KEY, res.getUri());
	doc.append(ResourceDAO.CRETIME_KEY, currentTime);
	doc.append(ResourceDAO.LASTMODTIME_KEY, currentTime);

	MongoCollection<Document> collection = context.getDatabaseManager()
			.getCollection(collectionName);

	collection.insertOne(doc);
	
}
 
Example #9
Source File: ITTestProjectionsAndFilter.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@Test
public final void runTestProjectExtractDayFilter() throws Exception {
  String sqlQuery = "select datefield from elasticsearch." + schema + "." + table + " where  extract(day from \"datefield\") = 10";
  verifyJsonInPlan(sqlQuery, new String[] {
    "[{\n" +
      "  \"from\" : 0,\n" +
      "  \"size\" : 4000,\n" +
      "  \"query\" : {\n" +
      "    \"script\" : {\n" +
      "      \"script\" : {\n" +
      "        \"inline\" : \"(def) ((doc[\\\"datefield\\\"].empty) ? false : ( LocalDateTime.ofInstant(Instant.ofEpochMilli(doc[\\\"datefield\\\"].date.millis), ZoneOffset.UTC).getDayOfMonth() == 10L ))\",\n" +
      "        \"lang\" : \"painless\"\n" +
      "      },\n" +
      "      \"boost\" : 1.0\n" +
      "    }\n" +
      "  },\n" +
      "  \"_source\" : {\n" +
      "    \"includes\" : [\n" +
      "      \"datefield\"\n" +
      "    ],\n" +
      "    \"excludes\" : [ ]\n" +
      "  }\n" +
      "}]"
  });

  testBuilder().sqlQuery(sqlQuery).unOrdered().baselineColumns("datefield")
      .baselineValues(new LocalDateTime(Timestamp.valueOf("2014-02-10 10:50:42")))
      .baselineValues(new LocalDateTime(Timestamp.valueOf("2014-02-10 10:50:42")))
      .go();
}
 
Example #10
Source File: EventReloaderJob.java    From openhab1-addons with Eclipse Public License 2.0 5 votes vote down vote up
private org.joda.time.DateTime getDateTime(String dateType, DateTime date, Date rangeDate) {
    org.joda.time.DateTime start;
    if (date.getTimeZone() == null) {
        if (date.isUtc()) {
            log.trace("{} is without timezone, but UTC", dateType);
            start = new org.joda.time.DateTime(rangeDate, DateTimeZone.UTC).toLocalDateTime()
                    .toDateTime(CalDavLoaderImpl.defaultTimeZone);
        } else {
            log.trace("{} is without timezone, not UTC", dateType);
            start = new LocalDateTime(rangeDate).toDateTime();
        }
    } else if (DateTimeZone.getAvailableIDs().contains(date.getTimeZone().getID())) {
        log.trace("{} is with known timezone: {}", dateType, date.getTimeZone().getID());
        start = new org.joda.time.DateTime(rangeDate, DateTimeZone.forID(date.getTimeZone().getID()));
    } else {
        // unknown timezone
        log.trace("{} is with unknown timezone: {}", dateType, date.getTimeZone().getID());
        start = new org.joda.time.DateTime(rangeDate, CalDavLoaderImpl.defaultTimeZone);
    }
    return start;
}
 
Example #11
Source File: JodaTimeFormattingTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testBindLocalDateTime() {
	MutablePropertyValues propertyValues = new MutablePropertyValues();
	propertyValues.add("localDateTime", new LocalDateTime(2009, 10, 31, 12, 0));
	binder.bind(propertyValues);
	assertEquals(0, binder.getBindingResult().getErrorCount());
	String value = binder.getBindingResult().getFieldValue("localDateTime").toString();
	assertTrue(value.startsWith("10/31/09"));
	assertTrue(value.endsWith("12:00 PM"));
}
 
Example #12
Source File: SVPlanDemoTest.java    From substitution-schedule-parser with Mozilla Public License 2.0 5 votes vote down vote up
@Test
public void demoTest3() throws IOException, JSONException {
    List<Document> docs = new ArrayList<>();
    docs.add(Jsoup.parse(html3));
    SubstitutionSchedule schedule = parser.parseSVPlanSchedule(docs);

    assertEquals(new LocalDateTime(2017, 5, 2, 7, 19), schedule.getLastChange());
    assertEquals(1, schedule.getDays().size());

    SubstitutionScheduleDay day = schedule.getDays().get(0);

    assertEquals(new LocalDate(2017, 5, 2), day.getDate());
    assertEquals(32, day.getSubstitutions().size());
    assertEquals(0, day.getMessages().size());

    for (Substitution subst : day.getSubstitutions()) {
        if (!subst.getSubject().equals("Profi")) assertTrue(subst.getClasses().size() >= 1);
        assertNotEmpty(subst.getLesson());
        assertNullOrNotEmpty(subst.getPreviousSubject());
        assertNotEmpty(subst.getSubject());
        assertNullOrNotEmpty(subst.getRoom());
        assertNullOrNotEmpty(subst.getTeacher());
        assertNullOrNotEmpty(subst.getPreviousTeacher());
        assertNullOrNotEmpty(subst.getDesc());
        assertNotEmpty(subst.getType());
    }
}
 
Example #13
Source File: TurnoverRepository_IntegTest.java    From estatio with Apache License 2.0 5 votes vote down vote up
@Test
public void findApprovedByConfigAndTypeAndFrequency() throws Exception {

    // given
    final Occupancy occupancy = Lease_enum.OxfTopModel001Gb.findUsing(serviceRegistry2).getOccupancies().first();
    final LocalDate turnoverDate = new LocalDate(2019, 1, 1);
    final Currency euro = Currency_enum.EUR.findUsing(serviceRegistry2);
    final LocalDateTime reportedAt = new LocalDateTime(2019, 1, 1, 12, 0);

    // when
    TurnoverReportingConfig config = turnoverReportingConfigRepository.findOrCreate(occupancy, Type.PRELIMINARY, null, occupancy.getStartDate(), Frequency.MONTHLY, euro);

    Turnover turnover1 = turnoverRepository.create(config, turnoverDate, Type.PRELIMINARY, Frequency.MONTHLY, Status.APPROVED, reportedAt, "someone", euro, null, null, null, null, false);
    Turnover turnover2 = turnoverRepository.create(config, turnoverDate.minusMonths(2), Type.PRELIMINARY, Frequency.MONTHLY, Status.APPROVED, reportedAt, "someone", euro, null, null, null, null, false);
    Turnover turnover3 = turnoverRepository.create(config, turnoverDate.minusMonths(1), Type.PRELIMINARY, Frequency.MONTHLY, Status.APPROVED, reportedAt, "someone", euro, null, null, null, null, false);
    Turnover turnover4 = turnoverRepository.create(config, turnoverDate.minusMonths(1).minusDays(1), Type.PRELIMINARY, Frequency.DAILY, Status.APPROVED, reportedAt, "someone", euro, null, null, null, null, false);
    Turnover turnover5 = turnoverRepository.create(config, turnoverDate.minusMonths(3), Type.PRELIMINARY, Frequency.MONTHLY, Status.NEW, reportedAt, "someone", euro, null, null, null, null, false);
    Turnover turnover6 = turnoverRepository.create(config, turnoverDate.minusMonths(3), Type.AUDITED, Frequency.MONTHLY, Status.NEW, reportedAt, "someone", euro, null, null, null, null, false);
    // then
    Assertions.assertThat(turnoverRepository.findApprovedByConfigAndTypeAndFrequency(config, Type.PRELIMINARY, Frequency.MONTHLY)).hasSize(3);
    Assertions.assertThat(turnoverRepository.findApprovedByConfigAndTypeAndFrequency(config, Type.PRELIMINARY, Frequency.DAILY)).hasSize(1);
    Assertions.assertThat(turnoverRepository.findApprovedByConfigAndTypeAndFrequency(config, Type.AUDITED, Frequency.MONTHLY)).hasSize(0);

    // and when
    turnover5.setStatus(Status.APPROVED);
    turnover6.setStatus(Status.APPROVED);
    // then
    Assertions.assertThat(turnoverRepository.findApprovedByConfigAndTypeAndFrequency(config, Type.PRELIMINARY, Frequency.MONTHLY)).hasSize(4);
    Assertions.assertThat(turnoverRepository.findApprovedByConfigAndTypeAndFrequency(config, Type.PRELIMINARY, Frequency.DAILY)).hasSize(1);
    Assertions.assertThat(turnoverRepository.findApprovedByConfigAndTypeAndFrequency(config, Type.AUDITED, Frequency.MONTHLY)).hasSize(1);

}
 
Example #14
Source File: Turnover.java    From estatio with Apache License 2.0 5 votes vote down vote up
public Turnover(
        final TurnoverReportingConfig config,
        final LocalDate date,
        final Type type,
        final Frequency frequency,
        final Status status,
        final LocalDateTime reportedAt,
        final String reportedBy,
        final Currency currency,
        final BigDecimal netAmount,
        final BigDecimal grossAmount,
        final BigInteger purchaseCount,
        final String comments,
        final boolean nonComparable){
    this();
    this.config = config;
    this.date = date;
    this.type = type;
    this.frequency = frequency;
    this.status = status;
    this.reportedAt = reportedAt;
    this.reportedBy = reportedBy;
    this.currency = currency;
    this.netAmount = netAmount;
    this.grossAmount = grossAmount;
    this.purchaseCount = purchaseCount;
    this.comments = comments;
    this.nonComparable = nonComparable;
}
 
Example #15
Source File: DateTimeUnit.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Converts dateUnit to Joda-Time DateTime with a specific chronology.
 *
 * @param chronology Chronology to use
 * @return Populated DateTime object
 */
public DateTime toJodaDateTime( Chronology chronology )
{
    try
    {
        return new DateTime( year, month, day, hour, minute, second, millis, chronology.withZone( DateTimeZone.forTimeZone( timeZone ) ) );
    }
    catch ( IllegalInstantException ex )
    {
        LocalDateTime localDateTime = new LocalDateTime( year, month, day, hour, minute, second, millis,
            chronology.withZone( DateTimeZone.forTimeZone( timeZone ) ) );

        return localDateTime.toLocalDate().toDateTimeAtStartOfDay();
    }
}
 
Example #16
Source File: TurnoverRepository_IntegTest.java    From estatio with Apache License 2.0 5 votes vote down vote up
@Test
public void upsert_works() throws Exception {

    // given
    final Occupancy occupancy = Lease_enum.OxfTopModel001Gb.findUsing(serviceRegistry2).getOccupancies().first();
    final LocalDateTime reportedAt = new LocalDateTime(2019, 1, 1, 12, 0);

    final LocalDate turnoverDate = new LocalDate(2019, 1, 1);
    final Currency euro = Currency_enum.EUR.findUsing(serviceRegistry2);
    final BigDecimal originalGrossAmount = new BigDecimal("1234.56");
    TurnoverReportingConfig config = turnoverReportingConfigRepository.findOrCreate(occupancy, Type.AUDITED, null, occupancy.getStartDate(), Frequency.MONTHLY, euro);
    Turnover turnover = turnoverRepository.create(config, turnoverDate, Type.AUDITED, Frequency.MONTHLY, Status.NEW, reportedAt, "someone", euro, null, originalGrossAmount, null, null, false);

    // when
    final LocalDateTime reportedAt2 = new LocalDateTime(2019, 1, 1, 13, 30);
    final BigDecimal updatedGrossAmount = new BigDecimal("1230.00");
    final Currency sek = Currency_enum.SEK.findUsing(serviceRegistry2);
    final BigDecimal netAmount = new BigDecimal("4321.00");
    Turnover turnover2 = turnoverRepository.upsert(config, turnoverDate, Type.AUDITED, Frequency.YEARLY, Status.APPROVED, reportedAt2, "someone else", sek, netAmount, updatedGrossAmount, BigInteger.valueOf(123), "changed", true);

    // then
    /* NOTE: config, date, type = unique,
    we consider frequency and currency immutable */
    assertThat(turnover).isSameAs(turnover2);
    assertThat(turnover2.getFrequency()).isEqualTo(Frequency.MONTHLY);
    assertThat(turnover2.getCurrency()).isEqualTo(euro);
    // mutable properties
    assertThat(turnover2.getStatus()).isEqualTo(Status.APPROVED);
    assertThat(turnover2.getReportedAt()).isEqualTo(reportedAt2);
    assertThat(turnover2.getReportedBy()).isEqualTo("someone else");
    assertThat(turnover2.getNetAmount()).isEqualTo(netAmount);
    assertThat(turnover2.getGrossAmount()).isEqualTo(updatedGrossAmount);
    assertThat(turnover2.getPurchaseCount()).isEqualTo(BigInteger.valueOf(123));
    assertThat(turnover2.getComments()).isEqualTo("changed");
    assertThat(turnover2.isNonComparable()).isTrue();
}
 
Example #17
Source File: TaskRepository.java    From estatio with Apache License 2.0 5 votes vote down vote up
private List<Task> findIncompleteForAndCreatedOnAfter(
        final Person personAssignedTo,
        final LocalDateTime createdOn) {
    return queryResultsCache.execute(
            () -> doFindIncompleteForAndCreatedOnAfter(personAssignedTo, createdOn),
            getClass(),
            "findIncompleteForAndCreatedOnAfter", personAssignedTo, createdOn);
}
 
Example #18
Source File: ESchoolParser.java    From substitution-schedule-parser with Mozilla Public License 2.0 5 votes vote down vote up
@NotNull
SubstitutionSchedule parseESchoolSchedule(Document doc) throws IOException, JSONException {
    SubstitutionSchedule schedule = SubstitutionSchedule.fromData(scheduleData);

    String infoString = doc.select("#Content table").first().select("td").get(1).ownText();
    Pattern pattern = Pattern.compile("Letzte Aktualisierung:\u00a0(\\d{2}.\\d{2}.\\d{4} - \\d{2}:\\d{2})");
    Matcher matcher = pattern.matcher(infoString);
    if (matcher.find()) {
        LocalDateTime lastChange = DateTimeFormat.forPattern("dd.MM.yyyy - HH:mm")
                .parseLocalDateTime(matcher.group(1));
        schedule.setLastChange(lastChange);
    }

    Elements titles = doc.select("center b");
    Elements tables = doc.select("table#DATA");

    if (!tables.get(0).text().contains("Keine Daten verfügbar")) {
        if (titles.size() != tables.size()) throw new IOException("Anzahl Überschriften != Anzahl Tabellen");

        for (int i = 0; i < titles.size(); i++) {
            SubstitutionScheduleDay day = new SubstitutionScheduleDay();
            day.setDate(ParserUtils.parseDate(titles.get(i).text()));
            parseTable(tables.get(i), day);
            schedule.addDay(day);
        }
    }

    schedule.setClasses(getAllClasses());
    schedule.setTeachers(getAllTeachers());
    return schedule;
}
 
Example #19
Source File: DateFormats.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
public LocalDateTime parse(String value) {
  if (formatter == null) {
    if (isEpochMillis) {
      return new LocalDateTime(Long.parseLong(value), ISOChronology.getInstanceUTC());
    } else {
      // isEpochSeconds
      return new LocalDateTime(Long.parseLong(value) * 1000, ISOChronology.getInstanceUTC());
    }
  }
  return formatter.parseLocalDateTime(value);
}
 
Example #20
Source File: TestDateTimeFormatter.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public void testParseLocalDateTime_monthDay_withDefaultYear_feb29() {
    Chronology chrono = GJChronology.getInstanceUTC();
    DateTimeFormatter f = DateTimeFormat
        .forPattern("M d H m")
        .withChronology(chrono)
        .withLocale(Locale.UK)
        .withDefaultYear(2012);
    
    assertEquals(new LocalDateTime(2012, 2, 29, 13, 40, 0, 0, chrono), f.parseLocalDateTime("2 29 13 40"));
}
 
Example #21
Source File: SVPlanDemoTest.java    From substitution-schedule-parser with Mozilla Public License 2.0 5 votes vote down vote up
@Test
public void demoTest1() throws IOException, JSONException {
    List<Document> docs = new ArrayList<>();
    docs.add(Jsoup.parse(html1));
    SubstitutionSchedule schedule = parser.parseSVPlanSchedule(docs);

    assertEquals(new LocalDateTime(2016, 9, 2, 11, 10), schedule.getLastChange());
    assertEquals(5, schedule.getDays().size());

    SubstitutionScheduleDay day = schedule.getDays().get(0);

    assertEquals(new LocalDate(2016, 9, 2), day.getDate());
    assertEquals(16, day.getSubstitutions().size());
    assertEquals(1, day.getMessages().size());
    assertEquals("Ordnungsdienst:9BR<br>", day.getMessages().get(0));

    for (Substitution subst : day.getSubstitutions()) {
        assertNotEmpty(subst.getLesson());
        assertNullOrNotEmpty(subst.getPreviousSubject());
        assertNullOrNotEmpty(subst.getRoom());
        assertNullOrNotEmpty(subst.getTeacher());
        assertNullOrNotEmpty(subst.getPreviousTeacher());
        assertNullOrNotEmpty(subst.getDesc());
        assertNotEmpty(subst.getType());
        if (!subst.getType().equals("Pausenaufsicht")) {
            assertEquals(1, subst.getClasses().size());
            assertNotEmpty(subst.getSubject());
        }
    }
}
 
Example #22
Source File: Times.java    From prayer-times-android with Apache License 2.0 5 votes vote down vote up
@Nullable
private static Pair<Alarm, LocalDateTime> getNextAlarm() {
    Pair<Alarm, LocalDateTime> pair = null;
    for (Times t : Times.getTimes()) {
        Pair<Alarm, LocalDateTime> nextAlarm = getNextAlarm(t);
        if (pair == null || pair.second == null || (nextAlarm != null && nextAlarm.second != null && pair.second.isAfter(nextAlarm.second))) {
            pair = nextAlarm;
        }
    }
    return pair;
}
 
Example #23
Source File: ExtendedJsonOutput.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@Override
public void writeDate(LocalDateTime value) throws IOException {
  gen.writeStartObject();
  gen.writeFieldName(ExtendedType.DATE.serialized);
  super.writeDate(value);
  gen.writeEndObject();
}
 
Example #24
Source File: TestDateTimeFormatter.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public void testParseLocalDateTime_simple() {
    assertEquals(new LocalDateTime(2004, 6, 9, 10, 20, 30), g.parseLocalDateTime("2004-06-09T10:20:30Z"));
    assertEquals(new LocalDateTime(2004, 6, 9, 10, 20, 30), g.parseLocalDateTime("2004-06-09T10:20:30+18:00"));
    assertEquals(new LocalDateTime(2004, 6, 9, 10, 20, 30), g.parseLocalDateTime("2004-06-09T10:20:30-18:00"));
    assertEquals(new LocalDateTime(2004, 6, 9, 10, 20, 30, 0, BUDDHIST_PARIS),
            g.withChronology(BUDDHIST_PARIS).parseLocalDateTime("2004-06-09T10:20:30Z"));
    try {
        g.parseDateTime("ABC");
        fail();
    } catch (IllegalArgumentException ex) {}
}
 
Example #25
Source File: GeneratedFileManager.java    From laozhongyi with MIT License 5 votes vote down vote up
public static void mkdirForHyperParameterConfig() {
    final String homeDir = System.getProperty("user.home");
    final String logDir = "hyper" + new LocalDateTime().toString();
    mHyperParameterConfigDirPath = FilenameUtils.concat(homeDir, logDir);
    try {
        FileUtils.forceMkdir(new File(mHyperParameterConfigDirPath));
    } catch (final IOException e) {
        throw new IllegalStateException(e);
    }
}
 
Example #26
Source File: TestDateTimeFormatterBuilder.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public void test_localPrintParseOffsetAndZone() {
    DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder()
        .appendPattern("yyyy-MM-dd HH:mm ").appendTimeZoneOffset("Z", true, 2, 2).appendLiteral(' ').appendTimeZoneId();
    DateTimeFormatter f = bld.toFormatter();
    
    DateTime dt = new DateTime(2007, 3, 4, 12, 30, 0, TOKYO);
    assertEquals("2007-03-04 12:30 +09:00 Asia/Tokyo", f.print(dt));
    
    LocalDateTime expected = new LocalDateTime(2007, 3, 4, 12, 30);
    assertEquals(expected, f.withZone(TOKYO).parseLocalDateTime("2007-03-04 12:30 +09:00 Asia/Tokyo"));
    assertEquals(expected, f.withZone(PARIS).parseLocalDateTime("2007-03-04 12:30 +09:00 Asia/Tokyo"));
}
 
Example #27
Source File: TaskRepository.java    From estatio with Apache License 2.0 5 votes vote down vote up
private List<Task> doFindIncompleteByUnassignedForRolesAndCreatedOnBefore(final List<PartyRoleType> roleTypes, final LocalDateTime createdOn) {
    return repositoryService.allMatches(
            new QueryDefault<>(
                    Task.class,
                    "findIncompleteByUnassignedForRolesAndCreatedOnBefore",
                    "roleTypes", roleTypes,
                    "createdOn", createdOn));
}
 
Example #28
Source File: TestDateTimeFormatterBuilder.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public void test_localParseWrongOffsetAndZone() {
    DateTimeFormatterBuilder bld = new DateTimeFormatterBuilder()
        .appendPattern("yyyy-MM-dd HH:mm ").appendTimeZoneOffset("Z", true, 2, 2).appendLiteral(' ').appendTimeZoneId();
    DateTimeFormatter f = bld.toFormatter();
    
    LocalDateTime expected = new LocalDateTime(2007, 3, 4, 12, 30);
    // parses offset time then adjusts to parsed zone
    assertEquals(expected, f.parseLocalDateTime("2007-03-04 12:30 +07:00 Asia/Tokyo"));
    // parses offset time then adjusts to requested zone
    assertEquals(expected, f.withZone(TOKYO).parseLocalDateTime("2007-03-04 12:30 +07:00 Asia/Tokyo"));
    // parses offset time returning offset zone (ignores zone)
    assertEquals(expected, f.withOffsetParsed().parseLocalDateTime("2007-03-04 12:30 +07:00 Asia/Tokyo"));
}
 
Example #29
Source File: ITTestDateTypeWithMultipleFormatter.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@Test
public final void runTestWithTimeFormatter() throws Exception {
  populateTimeFormatter();
  final String sql = "select field from elasticsearch." + schema + "." + table;
  verifyJsonInPlan(sql, new String[] {
    "[{\n" +
    "  \"from\" : 0,\n" +
    "  \"size\" : 4000,\n" +
    "  \"query\" : {\n" +
    "    \"match_all\" : {\n" +
    "      \"boost\" : 1.0\n" +
    "    }\n" +
    "  },\n" +
    "  \"_source\" : {\n" +
    "    \"includes\" : [\n" +
    "      \"field\"\n" +
    "    ],\n" +
    "    \"excludes\" : [ ]\n" +
    "  }\n" +
    "}]"});
  testBuilder()
    .sqlQuery(sql)
    .unOrdered()
    .baselineColumns("field")
    .baselineValues(new LocalDateTime(Timestamp.valueOf("1970-01-01 01:02:03.123")))
    .baselineValues(new LocalDateTime(Timestamp.valueOf("1970-01-01 01:01:15.000")))
    .baselineValues(new LocalDateTime(Timestamp.valueOf("1970-01-01 01:02:03.345")))
    .go();
}
 
Example #30
Source File: TestAllClassDataTypesAreSupported.java    From jfixture with MIT License 5 votes vote down vote up
@Test
public void creates_instance_of_LocalDateTime() {
    LocalDateTime localDateTime = fixture.create(LocalDateTime.class);
    assertThat(localDateTime, notNullValue());
    assertThat(localDateTime.getYear(), is(2001)); // LocalDateTime::toDate is not recommended
    assertThat(localDateTime.getMonthOfYear(), is(1));
    assertThat(localDateTime.getDayOfMonth(), is(1));
    assertThat(localDateTime.getHourOfDay(), is(12));
    assertThat(localDateTime.getMinuteOfHour(), is(34));
    assertThat(localDateTime.getSecondOfMinute(), is(56));
}