Example usage for java.time.format DateTimeFormatter ISO_LOCAL_DATE

List of usage examples for java.time.format DateTimeFormatter ISO_LOCAL_DATE

Introduction

In this page you can find the example usage for java.time.format DateTimeFormatter ISO_LOCAL_DATE.

Prototype

DateTimeFormatter ISO_LOCAL_DATE

To view the source code for java.time.format DateTimeFormatter ISO_LOCAL_DATE.

Click Source Link

Document

The ISO date formatter that formats or parses a date without an offset, such as '2011-12-03'.

Usage

From source file:Main.java

public static void main(String[] args) {
    Instant instant = Instant.parse("2014-07-16T10:15:30.00Z");
    LocalDate localDate = LocalDate.parse("2014-07-16", DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    LocalDate localDate2 = LocalDate.parse("2014-07-16", DateTimeFormatter.ISO_LOCAL_DATE);

    DateTimeFormatter strangeFormat = new DateTimeFormatterBuilder().appendValue(MONTH_OF_YEAR, 2)
            .appendLiteral("==").appendValue(YEAR, 4).appendLiteral("--").appendValue(DAY_OF_MONTH, 2)
            .toFormatter();//w  w w.java 2  s. c  o m

    LocalDate localDate3 = LocalDate.parse("07==2014--16", strangeFormat);

    System.out.println(instant);
    System.out.println(localDate);
    System.out.println(localDate2);
    System.out.println(localDate3);

    LocalDate date = Year.of(2014).atMonth(7).atDay(16);
    String strangeDateFormat = date.format(strangeFormat);

    System.out.println(strangeDateFormat);
}

From source file:de.lgblaumeiser.ptm.analysis.analyzer.HourComputer.java

@Override
public Collection<Collection<Object>> analyze(final Collection<String> parameter) {
    YearMonth requestedMonth = YearMonth.now();
    if (parameter.size() > 0) {
        requestedMonth = YearMonth.parse(Iterables.get(parameter, 0));
    }// w  w w . j a  v  a 2 s .c o  m
    Collection<Collection<Object>> result = Lists.newArrayList();
    result.add(Arrays.asList("Work Day", "Starttime", "Endtime", "Presence", "Worktime", "Breaktime",
            "Overtime", "Comment"));
    Duration overtime = Duration.ZERO;
    LocalDate currentday = requestedMonth.atDay(1);
    while (!currentday.isAfter(requestedMonth.atEndOfMonth())) {
        Collection<Booking> currentBookings = getBookingsForDay(currentday);
        if (hasCompleteBookings(currentBookings)) {
            String day = currentday.format(DateTimeFormatter.ISO_LOCAL_DATE);
            LocalTime starttime = Iterables.getFirst(currentBookings, null).getStarttime();
            LocalTime endtime = Iterables.getLast(currentBookings).getEndtime();
            Duration presence = calculatePresence(starttime, endtime);
            Duration worktime = calculateWorktime(currentBookings);
            Duration breaktime = calculateBreaktime(presence, worktime);
            Duration currentOvertime = calculateOvertime(worktime, currentday);
            overtime = overtime.plus(currentOvertime);
            result.add(Arrays.asList(day, starttime.format(DateTimeFormatter.ofPattern("HH:mm")),
                    endtime.format(DateTimeFormatter.ofPattern("HH:mm")), formatDuration(presence),
                    formatDuration(worktime), formatDuration(breaktime), formatDuration(overtime),
                    validate(worktime, breaktime)));
        }
        currentday = currentday.plusDays(1);
    }
    return result;
}

From source file:com.example.database.DatabaseApp.java

@Bean
public ObjectMapper jsonObjectMapper() {
    final JavaTimeModule module = new JavaTimeModule();
    module.addDeserializer(LocalDateTime.class,
            new LocalDateTimeDeserializer(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
    module.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ISO_LOCAL_DATE));
    final ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(module);//  w  ww  .j a va 2  s . c  o m
    mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
    return mapper;
}

From source file:com.example.api.ApiApp.java

@Bean
RestTemplate restTemplate(final RestTemplateBuilder restTemplateBuilder) {
    final SimpleModule datetimeModule = new SimpleModule();
    datetimeModule.addDeserializer(LocalDateTime.class,
            new LocalDateTimeDeserializer(DateTimeFormatter.ISO_LOCAL_DATE));
    datetimeModule.addDeserializer(LocalDate.class,
            new LocalDateDeserializer(DateTimeFormatter.ISO_LOCAL_DATE));

    final ObjectMapper mapper = Jackson2ObjectMapperBuilder.json().modules(datetimeModule)
            .propertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE)
            .featuresToEnable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES).build();

    return restTemplateBuilder.messageConverters(new MappingJackson2HttpMessageConverter(mapper)).build();
}

From source file:org.bedework.synch.cnctrs.file.FileConnectorInstance.java

@Override
public URI getUri() throws SynchException {
    try {/*from w  w w. j  a v a 2 s  .  com*/
        //Get yesterdays date
        final LocalDate yesterday = LocalDate.now().minus(1, ChronoUnit.DAYS);
        final String yesterdayStr = yesterday.format(DateTimeFormatter.ISO_LOCAL_DATE);

        final URI infoUri = new URI(info.getUri());
        return new URIBuilder().setScheme(infoUri.getScheme()).setHost(infoUri.getHost())
                .setPort(infoUri.getPort()).setPath(infoUri.getPath()).build();
    } catch (final SynchException se) {
        throw se;
    } catch (final Throwable t) {
        throw new SynchException(t);
    }
}

From source file:org.bedework.synch.cnctrs.orgSyncV2.OrgSyncV2ConnectorInstance.java

@Override
public URI getUri() throws SynchException {
    try {//from   ww w.ja va2  s.c  o  m
        //Get yesterdays date
        final LocalDate yesterday = LocalDate.now().minus(1, ChronoUnit.DAYS);
        final String yesterdayStr = yesterday.format(DateTimeFormatter.ISO_LOCAL_DATE);

        final URI infoUri = new URI(info.getUri());
        return new URIBuilder().setScheme(infoUri.getScheme()).setHost(infoUri.getHost())
                .setPort(infoUri.getPort()).setPath(infoUri.getPath())
                .setParameter("key", cnctr.getSyncher().decrypt(info.getPassword()))
                .setParameter("start_date", yesterdayStr).build();
    } catch (final SynchException se) {
        throw se;
    } catch (final Throwable t) {
        throw new SynchException(t);
    }
}

From source file:de.steilerdev.myVerein.server.controller.admin.EventManagementController.java

/**
 * Returns all events, that are taking place on a specified date. The date parameter needs to be formatted according to the following pattern: YYYY/MM/DD. This function is invoked by GETting the URI /api/admin/event/date
 * @param date The selected date, correctly formatted (YYYY/MM/DD)
 * @return An HTTP response with a status code. If the function succeeds, a list of events is returned, otherwise an error code is returned.
 *///from  w  w w  . j  a v a2 s.  co  m
@RequestMapping(value = "date", produces = "application/json", method = RequestMethod.GET)
public ResponseEntity<List<Event>> getEventsOfDate(@RequestParam String date, @CurrentUser User currentUser) {
    logger.trace("[" + currentUser + "] Getting events of date " + date);
    LocalDateTime startOfDay, endOfDay, startOfMonth, endOfMonth;
    ArrayList<Event> eventsOfDay = new ArrayList<>();
    try {
        // Get start of day and start of next day
        startOfDay = LocalDate.parse(date, DateTimeFormatter.ISO_LOCAL_DATE).atStartOfDay();
        endOfDay = startOfDay.plusDays(1);

        startOfMonth = LocalDate.of(startOfDay.getYear(), startOfDay.getMonth(), 1).atStartOfDay();
        endOfMonth = startOfMonth.plusMonths(1);
        logger.debug("[" + currentUser + "] Converted to date object: " + startOfDay.toString());
    } catch (DateTimeParseException e) {
        logger.warn("[" + currentUser + "] Unable to parse date: " + date + ": " + e.toString());
        return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
    }

    logger.debug("Getting all single day events...");
    eventsOfDay.addAll(eventRepository.findAllByStartDateTimeBetweenAndMultiDate(startOfDay, endOfDay, false));
    logger.debug("All single day events retrieved, got " + eventsOfDay.size() + " events so far");

    logger.debug("Getting all multi day events...");
    //Collecting all multi date events, that either start or end within the selected month (which means that events that are spanning over several months are not collected)
    eventsOfDay.addAll(Stream.concat(
            eventRepository.findAllByStartDateTimeBetweenAndMultiDate(startOfMonth, endOfMonth, true).stream(), //All multi date events starting within the month
            eventRepository.findAllByEndDateTimeBetweenAndMultiDate(startOfMonth, endOfMonth, true).stream()) //All multi date events ending within the month
            .distinct() //Removing all duplicated events
            .parallel()
            .filter(event -> event.getStartDate().isEqual(startOfDay.toLocalDate())
                    || event.getEndDate().isEqual(startOfDay.toLocalDate())
                    || (event.getEndDate().isAfter(endOfDay.toLocalDate())
                            && event.getStartDate().isBefore(startOfDay.toLocalDate()))) //Filter all multi date events that do not span over the date
            .collect(Collectors.toList()));
    logger.debug("All multi day events gathered, got " + eventsOfDay.size() + " events so far");

    if (eventsOfDay.isEmpty()) {
        logger.warn("[" + currentUser + "] The events list of " + date + " is empty");
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    } else {
        eventsOfDay.replaceAll(Event::getSendingObjectOnlyNameTimeId);
        logger.debug("[" + currentUser + "] Returning " + eventsOfDay.size() + " events for " + date);
        return new ResponseEntity<>(eventsOfDay, HttpStatus.OK);
    }
}

From source file:net.jmhertlein.alphonseirc.AlphonseBot.java

private void handleDadCommand(final String target, String sender, String[] args) {
    if (args.length == 1) {
        sendMessage(target, "Usage: !dad [left|list|say]");
        return;//w w  w.j  a v  a  2  s  .com
    }

    switch (args[1]) {
    case "left":
        ZonedDateTime now = ZonedDateTime.now();
        this.dadLeaveTimes.put(LocalDate.now(), LocalTime.now());
        sendMessage(target,
                "Marked dad's leave time as now (" + now.format(DateTimeFormatter.ISO_LOCAL_TIME) + ").");
        break;
    case "list":
        int num = 3;
        if (args.length == 3) {
            try {
                num = Integer.parseInt(args[2]);
                if (num > 10)
                    num = 10;
            } catch (NumberFormatException nfe) {
                sendMessage(target, "Error parsing " + args[2] + " into int: " + nfe.getMessage());
                sendMessage(target, "Usage: !dad list (optional: number, default 3, max 10)");
                return;
            }
        }

        final int prevDays = num;
        dadLeaveTimes.keySet().stream().sorted()
                .filter(date -> date.isAfter(LocalDate.now().minusDays(prevDays)))
                .map(date -> date.format(DateTimeFormatter.ISO_LOCAL_DATE) + " || "
                        + dadLeaveTimes.get(date).format(DateTimeFormatter.ISO_LOCAL_TIME))
                .forEach(leaveTime -> sendMessage(target, leaveTime));

        break;
    case "say":
        String msg;
        switch (gen.nextInt(9)) {
        case 0:
            msg = "TYPES LOUDLY";
            break;
        case 1:
            msg = "BREATHES DEEPLY";
            break;
        case 2:
            msg = "ANGRILY TYPES AN EMAIL";
            break;
        case 3:
            msg = "BACKSPACES WITH AUTHORITY";
            break;
        case 4:
            msg = "STRETCHES WHILE EXHALING";
            break;
        case 5:
            msg = "thinks about Happy Hour";
            break;
        case 6:
            msg = "browses Yahoo! news";
            break;
        case 7:
            msg = "tells everyone to GET BACK TO WORK";
            break;
        case 8:
            msg = "ignores Lantzer standing in front of his desk";
            break;
        default:
            msg = "Someone made nextInt() go too high";
            break;
        }

        this.sendAction(target, msg);
        break;
    default:
        System.out.println("Bad switch on " + args[1]);
    }

}

From source file:net.tradelib.apps.StrategyBacktest.java

public static void run(Strategy strategy) throws Exception {
    // Setup the logging
    System.setProperty("java.util.logging.SimpleFormatter.format",
            "%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS: %4$s: %5$s%n%6$s%n");
    LogManager.getLogManager().reset();
    Logger rootLogger = Logger.getLogger("");
    if (Boolean.parseBoolean(BacktestCfg.instance().getProperty("file.log", "true"))) {
        FileHandler logHandler = new FileHandler("diag.out", 8 * 1024 * 1024, 2, true);
        logHandler.setFormatter(new SimpleFormatter());
        logHandler.setLevel(Level.FINEST);
        rootLogger.addHandler(logHandler);
    }/* w  ww .  jav a 2 s  . co m*/

    if (Boolean.parseBoolean(BacktestCfg.instance().getProperty("console.log", "true"))) {
        ConsoleHandler consoleHandler = new ConsoleHandler();
        consoleHandler.setFormatter(new SimpleFormatter());
        consoleHandler.setLevel(Level.INFO);
        rootLogger.addHandler(consoleHandler);
    }

    rootLogger.setLevel(Level.INFO);

    // Setup Hibernate
    // Configuration configuration = new Configuration();
    // StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
    // SessionFactory factory = configuration.buildSessionFactory(builder.build());

    Context context = new Context();
    context.dbUrl = BacktestCfg.instance().getProperty("db.url");

    HistoricalDataFeed hdf = new SQLDataFeed(context);
    hdf.configure(BacktestCfg.instance().getProperty("datafeed.config", "config/datafeed.properties"));
    context.historicalDataFeed = hdf;

    HistoricalReplay hr = new HistoricalReplay(context);
    context.broker = hr;

    strategy.initialize(context);
    strategy.cleanupDb();

    long start = System.nanoTime();
    strategy.start();
    long elapsedTime = System.nanoTime() - start;
    System.out.println("backtest took " + String.format("%.2f secs", (double) elapsedTime / 1e9));

    start = System.nanoTime();
    strategy.updateEndEquity();
    strategy.writeExecutionsAndTrades();
    strategy.writeEquity();
    elapsedTime = System.nanoTime() - start;
    System.out
            .println("writing to the database took " + String.format("%.2f secs", (double) elapsedTime / 1e9));

    System.out.println();

    // Write the strategy totals to the database
    strategy.totalTradeStats();

    // Write the strategy report to the database and obtain the JSON
    // for writing it to the console.
    JsonObject report = strategy.writeStrategyReport();

    JsonArray asa = report.getAsJsonArray("annual_stats");

    String csvPath = BacktestCfg.instance().getProperty("positions.csv.prefix");
    if (!Strings.isNullOrEmpty(csvPath)) {
        csvPath += "-" + strategy.getLastTimestamp().toLocalDate().format(DateTimeFormatter.BASIC_ISO_DATE)
                + ".csv";
    }

    String ordersCsvPath = BacktestCfg.instance().getProperty("orders.csv.suffix");
    if (!Strings.isNullOrEmpty(ordersCsvPath)) {
        ordersCsvPath = strategy.getLastTimestamp().toLocalDate().format(DateTimeFormatter.BASIC_ISO_DATE) + "-"
                + strategy.getName() + ordersCsvPath;
    }

    String actionsPath = BacktestCfg.instance().getProperty("actions.file.suffix");
    if (!Strings.isNullOrEmpty(actionsPath)) {
        actionsPath = strategy.getLastTimestamp().toLocalDate().format(DateTimeFormatter.BASIC_ISO_DATE) + "-"
                + strategy.getName() + actionsPath;
    }

    // If emails are being send out
    String signalText = StrategyText.build(context.dbUrl, strategy.getName(),
            strategy.getLastTimestamp().toLocalDate(), "   ", csvPath, '|');

    System.out.println(signalText);
    System.out.println();

    if (!Strings.isNullOrEmpty(ordersCsvPath)) {
        StrategyText.buildOrdersCsv(context.dbUrl, strategy.getName(),
                strategy.getLastTimestamp().toLocalDate(), ordersCsvPath);
    }

    File actionsFile = Strings.isNullOrEmpty(actionsPath) ? null : new File(actionsPath);

    if (actionsFile != null) {
        FileUtils.writeStringToFile(actionsFile,
                signalText + System.getProperty("line.separator") + System.getProperty("line.separator"));
    }

    String message = "";

    if (asa.size() > 0) {
        // Sort the array
        TreeMap<Integer, Integer> map = new TreeMap<Integer, Integer>();
        for (int ii = 0; ii < asa.size(); ++ii) {
            int year = asa.get(ii).getAsJsonObject().get("year").getAsInt();
            map.put(year, ii);
        }

        for (int id : map.values()) {
            JsonObject jo = asa.get(id).getAsJsonObject();
            String yearStr = String.valueOf(jo.get("year").getAsInt());
            String pnlStr = String.format("$%,d", jo.get("pnl").getAsInt());
            String pnlPctStr = String.format("%.2f%%", jo.get("pnl_pct").getAsDouble());
            String endEqStr = String.format("$%,d", jo.get("end_equity").getAsInt());
            String ddStr = String.format("$%,d", jo.get("maxdd").getAsInt());
            String ddPctStr = String.format("%.2f%%", jo.get("maxdd_pct").getAsDouble());
            String str = yearStr + " PnL: " + pnlStr + ", PnL Pct: " + pnlPctStr + ", End Equity: " + endEqStr
                    + ", MaxDD: " + ddStr + ", Pct MaxDD: " + ddPctStr;
            message += str + "\n";
        }

        String pnlStr = String.format("$%,d", report.get("pnl").getAsInt());
        String pnlPctStr = String.format("%.2f%%", report.get("pnl_pct").getAsDouble());
        String ddStr = String.format("$%,d", report.get("avgdd").getAsInt());
        String ddPctStr = String.format("%.2f%%", report.get("avgdd_pct").getAsDouble());
        String gainToPainStr = String.format("%.4f", report.get("gain_to_pain").getAsDouble());
        String str = "\nAvg PnL: " + pnlStr + ", Pct Avg PnL: " + pnlPctStr + ", Avg DD: " + ddStr
                + ", Pct Avg DD: " + ddPctStr + ", Gain to Pain: " + gainToPainStr;
        message += str + "\n";
    } else {
        message += "\n";
    }

    // Global statistics
    JsonObject jo = report.getAsJsonObject("total_peak");
    String dateStr = jo.get("date").getAsString();
    int maxEndEq = jo.get("equity").getAsInt();
    jo = report.getAsJsonObject("total_maxdd");
    double cash = jo.get("cash").getAsDouble();
    double pct = jo.get("pct").getAsDouble();
    message += "\n" + "Total equity peak [" + dateStr + "]: " + String.format("$%,d", maxEndEq) + "\n"
            + String.format("Current Drawdown: $%,d [%.2f%%]", Math.round(cash), pct) + "\n";

    if (report.has("latest_peak") && report.has("latest_maxdd")) {
        jo = report.getAsJsonObject("latest_peak");
        LocalDate ld = LocalDate.parse(jo.get("date").getAsString(), DateTimeFormatter.ISO_DATE);
        maxEndEq = jo.get("equity").getAsInt();
        jo = report.getAsJsonObject("latest_maxdd");
        cash = jo.get("cash").getAsDouble();
        pct = jo.get("pct").getAsDouble();
        message += "\n" + Integer.toString(ld.getYear()) + " equity peak ["
                + ld.format(DateTimeFormatter.ISO_DATE) + "]: " + String.format("$%,d", maxEndEq) + "\n"
                + String.format("Current Drawdown: $%,d [%.2f%%]", Math.round(cash), pct) + "\n";
    }

    message += "\n" + "Avg Trade PnL: "
            + String.format("$%,d", Math.round(report.get("avg_trade_pnl").getAsDouble())) + ", Max DD: "
            + String.format("$%,d", Math.round(report.get("maxdd").getAsDouble())) + ", Max DD Pct: "
            + String.format("%.2f%%", report.get("maxdd_pct").getAsDouble()) + ", Num Trades: "
            + Integer.toString(report.get("num_trades").getAsInt());

    System.out.println(message);

    if (actionsFile != null) {
        FileUtils.writeStringToFile(actionsFile, message + System.getProperty("line.separator"), true);
    }

    if (Boolean.parseBoolean(BacktestCfg.instance().getProperty("email.enabled", "false"))) {
        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", "smtp.sendgrid.net");
        props.put("mail.smtp.port", "587");

        String user = BacktestCfg.instance().getProperty("email.user");
        String pass = BacktestCfg.instance().getProperty("email.pass");

        Session session = Session.getInstance(props, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(user, pass);
            }
        });

        MimeMessage msg = new MimeMessage(session);
        try {
            msg.setFrom(new InternetAddress(BacktestCfg.instance().getProperty("email.from")));
            msg.addRecipients(RecipientType.TO, BacktestCfg.instance().getProperty("email.recipients"));
            msg.setSubject(strategy.getName() + " Report ["
                    + strategy.getLastTimestamp().format(DateTimeFormatter.ISO_LOCAL_DATE) + "]");
            msg.setText("Positions & Signals\n" + signalText + "\n\nStatistics\n" + message);
            Transport.send(msg);
        } catch (Exception ee) {
            Logger.getLogger("").warning(ee.getMessage());
        }
    }

    if (Boolean.parseBoolean(BacktestCfg.instance().getProperty("sftp.enabled", "false"))) {
        HashMap<String, String> fileMap = new HashMap<String, String>();
        if (!Strings.isNullOrEmpty(actionsPath))
            fileMap.put(actionsPath, actionsPath);
        if (!Strings.isNullOrEmpty(ordersCsvPath))
            fileMap.put(ordersCsvPath, ordersCsvPath);
        String user = BacktestCfg.instance().getProperty("sftp.user");
        String pass = BacktestCfg.instance().getProperty("sftp.pass");
        String host = BacktestCfg.instance().getProperty("sftp.host");
        SftpUploader sftp = new SftpUploader(host, user, pass);
        sftp.upload(fileMap);
    }
}

From source file:org.apache.hadoop.hive.metastore.HiveProtoEventsCleanerTask.java

/**
 * Compute the expired date partition, using the underlying clock in UTC time.
 *//*from  w  ww .ja  v a  2s  .c o  m*/
private static void computeExpiredDatePtn(long ttl) {
    // Use UTC date to ensure reader date is same on all timezones.
    LocalDate expiredDate = LocalDateTime.ofEpochSecond((clock.getTime() - ttl) / 1000, 0, ZoneOffset.UTC)
            .toLocalDate();
    expiredDatePtn = "date=" + DateTimeFormatter.ISO_LOCAL_DATE.format(expiredDate);
}