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

The following examples show how to use java.time.LocalDateTime#getDayOfYear() . 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
/** @param epochSecond in Unix Epoch Time [seconds]
 * @return the time in the AMoDeus framework as an integer for the {@link LocalDateTime}
 * @param localDateTime and the simulation date @param simDate */
private int ldtToAmodeus(LocalDateTime localDateTime, LocalDate localDate, Long epochSecond) {
    int day = localDateTime.getDayOfYear() - localDate.getDayOfYear();
    int amodeusTime = day * 3600 * 24 //
            + localDateTime.getHour() * 3600//
            + localDateTime.getMinute() * 60 //
            + localDateTime.getSecond();
    if (amodeusTime < 0) {
        System.err.println("amodeus time is smaller than zero...");
        if (Objects.nonNull(epochSecond))
            System.err.println("unxTime:     " + epochSecond);
        System.err.println("ldt:         " + localDateTime.toString());
        System.err.println("simDate:     " + localDate.toString());
        System.err.println("amodeustime: " + amodeusTime);
    }
    GlobalAssert.that(amodeusTime >= 0);
    return amodeusTime;
}
 
Example 2
/** Format date and time in a 'compact' way.
  *
  *  <p>If the time stamp falls within today, only hours .. seconds are displayed.
  *  For a time stamp on a different day from today, the date and time without seconds shown.
  *  For a time in different year, only the date is shown.
  *
  *  @param timestamp {@link Instant}
  *  @return Date and time of the data in preferred text format
  */
 public static String formatCompactDateTime(final Instant timestamp)
 {
    if (timestamp == null)
        return "?";

    final LocalDateTime now = LocalDateTime.now();
    final LocalDateTime local = LocalDateTime.ofInstant(timestamp, zone);

    if (now.getYear() == local.getYear())
    {
        // Same day, show time down to HH:mm:ss
        if (now.getDayOfYear() == local.getDayOfYear())
            return TIME_FORMAT.format(timestamp);
        else
            // Different day, same year, show month, day, down to minutes
            return MONTH_FORMAT.format(timestamp);
    }
    else
        // Different year, show yyyy-MM-dd";
        return DATE_FORMAT.format(timestamp);
}
 
Example 3
Source Project: archivo   File: DateUtils.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static String formatRecordedOnDateTime(LocalDateTime dateTime) {
    if (dateTime == null) {
        return "";
    }

    StringBuilder sb = new StringBuilder();
    sb.append("Recorded ");

    if (dateTime.getDayOfYear() == today) {
        sb.append("today");
    } else if (dateTime.getDayOfYear() == yesterday) {
        sb.append("yesterday");
    } else if (dateTime.getYear() == currentYear) {
        // Don't include the year for recordings from the current year
        sb.append(dateTime.format(DATE_RECORDED_SHORT_DATE_FORMATTER));
    } else {
        sb.append(dateTime.format(DATE_RECORDED_LONG_DATE_FORMATTER));
    }

    sb.append(" at ");
    sb.append(dateTime.format(DATE_RECORDED_TIME_FORMATTER));

    return sb.toString();
}
 
Example 4
private static List<Map<String, Object>> getDayData(int startYear, int startMonth, int startDay){
    List<Map<String, Object>> data = new ArrayList<>();
    LocalDateTime start = LocalDateTime.of(startYear, startMonth, startDay, 0, 0, 0, 0);
    LocalDateTime end = LocalDateTime.now();
    while(start.isBefore(end)) {
        String date = TimeUtils.toString(start, "yyyy-MM-dd");
        int dayofweek = start.getDayOfWeek().getValue();
        int dayofyear = start.getDayOfYear();
        int weekofyear = ((dayofyear-1) / 7)+1;
        int month = start.getMonth().getValue();
        int dayofmonth = start.getDayOfMonth();
        int quarter = ((month-1) / 3) + 1;
        int year = start.getYear();
        Map<String, Object> map = new HashMap<>();
        map.put("day_str", date+" 00:00:00");
        map.put("dayofweek", dayofweek);
        map.put("dayofyear", dayofyear);
        map.put("weekofyear", weekofyear);
        map.put("month", month);
        map.put("dayofmonth", dayofmonth);
        map.put("quarter", quarter);
        map.put("year", year);
        data.add(map);
        start = start.plusDays(1);
    }
    return data;
}
 
Example 5
Source Project: jackcess   File: DefaultDateFunctions.java    License: Apache License 2.0 5 votes vote down vote up
private static int getDayDiff(LocalDateTime ldt1, LocalDateTime ldt2) {
  int y1 = ldt1.getYear();
  int d1 = ldt1.getDayOfYear();
  int y2 = ldt2.getYear();
  int d2 = ldt2.getDayOfYear();
  while(y2  > y1) {
    ldt2 = ldt2.minusYears(1);
    d2 += ldt2.range(ChronoField.DAY_OF_YEAR).getMaximum();
    y2 = ldt2.getYear();
  }
  return d2 - d1;
}
 
Example 6
Source Project: archivo   File: DateUtils.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static String formatRecordedOnDate(LocalDateTime dateTime) {
    if (dateTime.getDayOfYear() == today) {
        return "Today";
    } else if (dateTime.getDayOfYear() == yesterday) {
        return "Yesterday";
    } else if (dateTime.getYear() == currentYear) {
        // Don't include the year for recordings from the current year
        return dateTime.format(DATE_RECORDED_SHORT_DATE_FORMATTER);
    } else {
        return dateTime.format(DATE_RECORDED_LONG_DATE_FORMATTER);
    }
}
 
Example 7
/**
 * monitor every group.
 */
@Async(value = "mgrAsyncExecutor")
public void transMonitorByGroupId(CountDownLatch latch, int groupId) {
    try {
        Instant startTimem = Instant.now();//start time
        Long useTimeSum = 0L;
        LocalDateTime start = LocalDateTime.now(); //createTime of monitor info
        LocalDateTime createTime = start;
        do {
            List<TbTransHash> transHashList = transHashService
                .qureyUnStatTransHashList(groupId);
            log.info("=== groupId:{} transHashList:{}", groupId, transHashList.size());
            if (transHashList.size() == 0) {
                log.debug("transMonitorByGroupId jump over. transHashList is empty");
                return;
            }

            if (checkUnusualMax(groupId)) {
                return;
            }

            //monitor
            for (TbTransHash trans : transHashList) {
                if (createTime.getDayOfYear() != trans.getBlockTimestamp().getDayOfYear()
                    || start == createTime) {
                    log.info(
                        "============== createTime:{} blockTimestamp:{}",
                        createTime,
                        trans.getBlockTimestamp());
                    log.info(
                        "============== createData:{} blockTimestampData:{}",
                        createTime.getDayOfYear(),
                        trans.getBlockTimestamp().getDayOfYear());
                    createTime = trans.getBlockTimestamp();
                }
                monitorTransHash(groupId, trans, createTime);
            }

            //monitor useTime
            useTimeSum = Duration.between(startTimem, Instant.now()).getSeconds();
            log.debug("monitor groupId:{} useTimeSum:{}s maxTime:{}s", groupId, useTimeSum,
                cProperties.getTransMonitorTaskFixedRate());
        } while (useTimeSum < cProperties.getTransMonitorTaskFixedRate());
        log.info("=== end monitor. groupId:{} allUseTime:{}s", groupId, useTimeSum);
    } catch (Exception ex) {
        log.error("fail transMonitorByGroupId, group:{}", groupId, ex);
    } finally {
        if (Objects.nonNull(latch)) {
            // finish one group, count down
            latch.countDown();
        }
    }
}
 
Example 8
/**
 * This sets off a verbose message.
 *
 * @param s             the message that will be sent
 * @param force_console whether the verbose message should appear in the console even when verbose for console is deactivated.
 * @param error         whether the message should be marked as an error
 */
public void sendVerboseMessage(final String s, final boolean force_console, final boolean error)
{
    // Remove color codes
    final String logMessage = ChatColor.stripColor(s);

    if (writeToFile) {
        try {
            // Get the logfile that is in use currently or create a new one if needed.
            final LocalDateTime now = LocalDateTime.now();

            // Doesn't need to check for logFile == null as the currentDayOfYear will be -1 in the beginning.
            if (currentDayOfYear != now.getDayOfYear() || !logFile.exists()) {
                currentDayOfYear = now.getDayOfYear();
                logFile = FileUtil.createFile(new File(AACAdditionPro.getInstance().getDataFolder().getPath() + "/logs/" + now.format(DateTimeFormatter.ISO_LOCAL_DATE) + ".log"));
            }

            // Reserve the required builder size.
            // Time length is always 12, together with 2 brackets and one space this will result in 15.
            final StringBuilder verboseMessage = new StringBuilder(15 + logMessage.length());
            // Add the beginning of the PREFIX
            verboseMessage.append('[');
            // Get the current time
            verboseMessage.append(now.format(DateTimeFormatter.ISO_LOCAL_TIME));

            // Add a 0 if it is too short
            // Technically only 12, but we already appended the "[", thus one more.
            while (verboseMessage.length() < 13) {
                verboseMessage.append('0');
            }

            // Add the rest of the PREFIX and the message
            verboseMessage.append("] ");
            verboseMessage.append(logMessage);
            verboseMessage.append('\n');

            // Log the message
            Files.write(logFile.toPath(), verboseMessage.toString().getBytes(), StandardOpenOption.APPEND);
        } catch (final IOException e) {
            AACAdditionPro.getInstance().getLogger().log(Level.SEVERE, "Something went wrong while trying to write to the log file.", e);
        }
    }

    if (writeToConsole || force_console) {
        AACAdditionPro.getInstance().getLogger().log(error ?
                                                     Level.SEVERE :
                                                     Level.INFO, logMessage);
    }

    // Prevent errors on disable as of scheduling
    if (allowedToRegisterTasks && writeToPlayers) {
        Bukkit.getScheduler().runTask(AACAdditionPro.getInstance(), () -> {
            for (User user : UserManager.getVerboseUsers()) {
                user.getPlayer().sendMessage(PRE_STRING + s);
            }
        });
    }
}