Java Code Examples for java.time.LocalDateTime#parse()

The following examples show how to use java.time.LocalDateTime#parse() . These examples are extracted from open source projects. 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 Project: copybook4java   File: StringToLocalDateTime.java    License: MIT License 6 votes vote down vote up
@Override
public byte[] from(Object value, int length, int decimals, boolean addPadding) {
    if(value == null) {
        if(this.defaultValue != null) {
            value = LocalDateTime.parse(this.defaultValue, formatter);

        } else {
            return null;
        }
    }

    byte[] strBytes = ((LocalDateTime)value).format(this.formatter).getBytes(this.charset);
    if (strBytes.length > length) {
        throw new TypeConverterException("Field to small for value: " + length + " < " + strBytes.length);
    }

    if (addPadding) {
        strBytes = padBytes(strBytes, length);
    }

    return strBytes;
}
 
Example 2
/**
 * @return a new instance of {@link GITMergeUnit}.
 * @throws MergeUnitException
 */
public static GITMergeUnit create(final IConfiguration configuration, final Path path, final InputStream is)
		throws MergeUnitException {

	final String host = configuration.getSftpConfiguration().getHost();
	final MergeUnitStatus status = getStatus(configuration, path);
	final List<String> inputLines = getLinesOfInputStream(is);
	final String repository = getProperty(REPOSITORY, inputLines);
	final LocalDateTime date = LocalDateTime.parse(getProperty(DATE, inputLines),
			DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
	final String commitId = getProperty(COMMID_ID, inputLines);
	final String sourceBranch = getProperty(SOURCE_BRANCH, inputLines);
	final String targetBranch = getProperty(TARGET_BRANCH, inputLines);
	final String fileName = path.getFileName().toString();
	final List<String> affectedFiles = inputLines.stream().filter(line -> line.startsWith(WORKING_COPY_FILE))
			.collect(AFFECTED_FILES_COLLECTOR);

	final GITMergeUnit mergeUnit = new GITMergeUnit(host, repository, date, commitId, sourceBranch, targetBranch,
			fileName, affectedFiles, configuration);
	mergeUnit.setStatus(status);
	mergeUnit.setRemotePath(path.toString().replace('\\', '/'));
	return mergeUnit;
}
 
Example 3
private List<String> getBetweenDateWithTwoSecond(String start, String end) {
  TimeZone.setDefault(TimeZone.getTimeZone("GMT+8"));
  DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
  List<String> list = new ArrayList<>();
  LocalDateTime startDate = LocalDateTime.parse(start);
  LocalDateTime endDate = LocalDateTime.parse(end);

  long distance = ChronoUnit.SECONDS.between(startDate, endDate);
  if (distance < 1) {
    return list;
  }
  Stream.iterate(startDate, d -> {
    return d.plusSeconds(2);
  }).limit((distance / 2) + 1).forEach(f -> {
    list.add(f.format(formatter));
  });
  return list;
}
 
Example 4
/**
 * convert String to localDateTime.
 */
public static LocalDateTime string2LocalDateTime(String time, String format) {
    if (StringUtils.isBlank(time)) {
        log.info("string2LocalDateTime. time is null");
        return null;
    }
    if (StringUtils.isBlank(format)) {
        log.info("string2LocalDateTime. format is null");
        format = DEFAULT_DATE_TIME_FORMAT;
    }
    DateTimeFormatter df = DateTimeFormatter.ofPattern(format);
    return LocalDateTime.parse(time, df);
}
 
Example 5
Source Project: tutorials   File: ContactAppUnitTest.java    License: MIT License 5 votes vote down vote up
@Test
public void givenJsonFormatAnnotationAndJava8DateType_whenGet_thenReturnExpectedDateFormat() throws IOException, ParseException {
    ResponseEntity<String> response = restTemplate.getForEntity(url + "/contacts", String.class);

    assertEquals(200, response.getStatusCodeValue());

    List<Map<String, String>> respMap = mapper.readValue(response.getBody(), new TypeReference<List<Map<String, String>>>(){});

    LocalDate birthdayDate = LocalDate.parse(respMap.get(0).get("birthday"), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    LocalDateTime lastUpdateTime = LocalDateTime.parse(respMap.get(0).get("lastUpdate"), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

    assertNotNull(birthdayDate);
    assertNotNull(lastUpdateTime);
}
 
Example 6
Source Project: nifi   File: TimeAdapter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Date unmarshal(String date) throws Exception {
    final LocalDateTime now = LocalDateTime.now();
    final DateTimeFormatter parser = new DateTimeFormatterBuilder().appendPattern(DEFAULT_TIME_FORMAT)
            .parseDefaulting(ChronoField.YEAR, now.getYear())
            .parseDefaulting(ChronoField.MONTH_OF_YEAR, now.getMonthValue())
            .parseDefaulting(ChronoField.DAY_OF_MONTH, now.getDayOfMonth())
            .parseDefaulting(ChronoField.MILLI_OF_SECOND, 0)
            .toFormatter(Locale.US);
    final LocalDateTime parsedDateTime = LocalDateTime.parse(date, parser);
    return Date.from(parsedDateTime.toInstant(ZONE_ID.getRules().getOffset(now)));
}
 
Example 7
Source Project: java8-tutorial   File: LocalDateTime1.java    License: MIT License 5 votes vote down vote up
public static void main(String[] args) {

        LocalDateTime sylvester = LocalDateTime.of(2014, Month.DECEMBER, 31, 23, 59, 59);

        DayOfWeek dayOfWeek = sylvester.getDayOfWeek();
        System.out.println(dayOfWeek);      // WEDNESDAY

        Month month = sylvester.getMonth();
        System.out.println(month);          // DECEMBER

        long minuteOfDay = sylvester.getLong(ChronoField.MINUTE_OF_DAY);
        System.out.println(minuteOfDay);    // 1439

        Instant instant = sylvester
                .atZone(ZoneId.systemDefault())
                .toInstant();

        Date legacyDate = Date.from(instant);
        System.out.println(legacyDate);     // Wed Dec 31 23:59:59 CET 2014


        DateTimeFormatter formatter =
                DateTimeFormatter
                        .ofPattern("MMM dd, yyyy - HH:mm");

        LocalDateTime parsed = LocalDateTime.parse("Nov 03, 2014 - 07:13", formatter);
        String string = parsed.format(formatter);
        System.out.println(string);     // Nov 03, 2014 - 07:13
    }
 
Example 8
Source Project: poiji   File: DefaultCasting.java    License: MIT License 5 votes vote down vote up
private LocalDateTime localDateTimeValue(String value, String sheetName, int row, int col, PoijiOptions options) {
    if (options.getDateTimeRegex() != null && !value.matches(options.getDateTimeRegex())) {
        return options.preferNullOverDefault() ? null : LocalDateTime.now();
    } else {
        try {
            return LocalDateTime.parse(value, options.dateTimeFormatter());
        } catch (DateTimeParseException e) {
            return onError(value, sheetName, row, col, e, options.preferNullOverDefault() ? null : LocalDateTime.now());
        }
    }
}
 
Example 9
@Test(dataProvider="sampleToString")
public void test_parse(int y, int month, int d, int h, int m, int s, int n, String text) {
    LocalDateTime t = LocalDateTime.parse(text);
    assertEquals(t.getYear(), y);
    assertEquals(t.getMonth().getValue(), month);
    assertEquals(t.getDayOfMonth(), d);
    assertEquals(t.getHour(), h);
    assertEquals(t.getMinute(), m);
    assertEquals(t.getSecond(), s);
    assertEquals(t.getNano(), n);
}
 
Example 10
@Test
public void testGenerateOneTimeCronExpression_YearBreak() {

    final DateTimeFormatter f = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    final LocalDateTime dateTime = LocalDateTime.parse("2018-12-31 23:56:59", f);
    final Clock mockClockInASock = mock(Clock.class);
    when(mockClockInASock.instant()).thenReturn(dateTime.toInstant(ZoneOffset.UTC));

    final CronHelper cronHelper = new CronHelper(mockClockInASock);

    assertThat(cronHelper.generateOneTimeCronExpression(5)).isEqualTo("cron(2 0 1 1 ? 2019)");
}
 
Example 11
@RequestMapping(value = EVCHARGE_URL, method = RequestMethod.PUT)
@CrossOrigin(origins = CROSS_ORIGIN_URL)
public void setEnergyDemand(HttpServletResponse response,
                            @RequestParam(value = "applianceid") String applianceId,
                            @RequestParam(value = "evid") Integer evId,
                            @RequestParam(value = "socCurrent", required = false) Integer socCurrent,
                            @RequestParam(value = "socRequested", required = false) Integer socRequested,
                            @RequestParam(value = "chargeEnd", required = false) String chargeEndString
) {
    synchronized (lock) {
        try {
            LocalDateTime chargeEnd = null;
            if (chargeEndString != null) {
                chargeEnd = LocalDateTime.parse(chargeEndString);
            }
            logger.debug("{}: Received energy request: evId={} socCurrent={} socRequested={} chargeEnd={}",
                    applianceId, evId, socCurrent, socRequested, chargeEnd);
            Appliance appliance = ApplianceManager.getInstance().findAppliance(applianceId);
            if (appliance != null) {
                appliance.setEnergyDemand(LocalDateTime.now(), evId, socCurrent, socRequested, chargeEnd);
            } else {
                logger.error("{}: Appliance not found", applianceId);
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            }
        } catch (Throwable e) {
            logger.error("Error in " + getClass().getSimpleName(), e);
        }
    }
}
 
Example 12
@Override
public Date unmarshal(String s) throws Exception {
	try {
		// Format "YYYY-MM-DDThh:mm:ssZ" / "YYYY-MM-DDThh:mm:ss+hh:mm" / "YYYY-MM-DDThh:mm:ss-hh:mm"
		return Date.from(ZonedDateTime.parse(s).toInstant());
	} catch(Exception e) {
		try {
			// Format "YYYY-MM-DDThh:mm:ss" (uses current timezone of the server)
			final LocalDateTime parsedWithoutTimezone = LocalDateTime.parse(s);
			return Date.from(parsedWithoutTimezone.atZone(ZoneId.systemDefault()).toInstant());
		} catch(Exception e2) {
			return new SimpleDateFormat(AGN_FORMAT).parse(s);
		}
	}
   }
 
Example 13
@Test(expectedExceptions=NullPointerException.class)
public void factory_parse_nullText() {
    LocalDateTime.parse((String) null);
}
 
Example 14
@Test(expectedExceptions=NullPointerException.class)
public void factory_parse_formatter_nullText() {
    DateTimeFormatter f = DateTimeFormatter.ofPattern("y M d H m s");
    LocalDateTime.parse((String) null, f);
}
 
Example 15
Source Project: basic-tools   File: Dates.java    License: MIT License 4 votes vote down vote up
public static LocalDateTime parseToLDT(String text) {
    return LocalDateTime.parse(standardDateTime(text), DateTimeFormatter.ofPattern("yyyyMMddHHmmss", Locale.CHINA));
}
 
Example 16
@Test(expectedExceptions=NullPointerException.class)
public void factory_parse_nullText() {
    LocalDateTime.parse((String) null);
}
 
Example 17
@Test(expectedExceptions=DateTimeParseException.class)
public void factory_parse_invalidValue() {
    LocalDateTime.parse("2008-06-31T11:15");
}
 
Example 18
@Override
public LocalDateTime fromString( String string )
{
    return LocalDateTime.parse( string );
}
 
Example 19
public static Object unWrapper(RexLiteral rexLiteral) {
    if (rexLiteral.isNull()) {
        return null;
    }
    RelDataType type = rexLiteral.getType();
    SqlTypeName sqlTypeName = type.getSqlTypeName();
    switch (sqlTypeName) {
        case BOOLEAN:
        case SMALLINT:
        case TINYINT:
        case INTEGER:
        case BIGINT:
        case DECIMAL:
        case FLOAT:
        case REAL:
        case DOUBLE:
            return rexLiteral.getValue();
        case DATE: {
            Integer valueAs = (Integer) rexLiteral.getValue4();
            return LocalDate.ofEpochDay(valueAs);
        }
        case TIME: {
            Integer value = (Integer) rexLiteral.getValue4();
            return LocalTime.ofNanoOfDay(TimeUnit.MILLISECONDS.toNanos(value));
        }
        case TIME_WITH_LOCAL_TIME_ZONE:
            break;
        case TIMESTAMP:
            String s = rexLiteral.toString();
            DateTimeFormatter dateTimeFormatter = new DateTimeFormatterBuilder()
                    .parseCaseInsensitive()
                    .append(ISO_LOCAL_DATE)
                    .appendLiteral(' ')
                    .append(ISO_LOCAL_TIME)
                    .toFormatter();
            return LocalDateTime.parse(s, dateTimeFormatter);
        case TIMESTAMP_WITH_LOCAL_TIME_ZONE:
            break;
        case INTERVAL_YEAR:
            break;
        case INTERVAL_YEAR_MONTH:
            break;
        case INTERVAL_MONTH:
            break;
        case INTERVAL_DAY:
            break;
        case INTERVAL_DAY_HOUR:
            break;
        case INTERVAL_DAY_MINUTE:
            break;
        case INTERVAL_DAY_SECOND:
            break;
        case INTERVAL_HOUR:
            break;
        case INTERVAL_HOUR_MINUTE:
            break;
        case INTERVAL_HOUR_SECOND:
            break;
        case INTERVAL_MINUTE:
            break;
        case INTERVAL_MINUTE_SECOND:
            break;
        case INTERVAL_SECOND:
            break;
        case CHAR:
        case VARCHAR:
            return ((NlsString) rexLiteral.getValue()).getValue();
        case BINARY:
        case VARBINARY:
            return ((org.apache.calcite.avatica.util.ByteString) rexLiteral.getValue()).getBytes();
        case NULL:
            return null;
        case ANY:
            break;
        case SYMBOL:
            break;
        case MULTISET:
            break;
        case ARRAY:
            break;
        case MAP:
            break;
        case DISTINCT:
            break;
        case STRUCTURED:
            break;
        case ROW:
            break;
        case OTHER:
            break;
        case CURSOR:
            break;
        case COLUMN_LIST:
            break;
        case DYNAMIC_STAR:
            break;
        case GEOMETRY:
            break;
    }
    throw new UnsupportedOperationException();
}
 
Example 20
/**
 * 字符串转换日期类型
 *
 * @param timeStr    日期字符串
 * @param timeFormat 日期格式
 * @return
 */
public static LocalDateTime parserDateTime(String timeStr, TimeFormat timeFormat) {
    return LocalDateTime.parse(timeStr, timeFormat.formatter);
}