Example usage for org.apache.commons.lang3.time DateUtils truncate

List of usage examples for org.apache.commons.lang3.time DateUtils truncate

Introduction

In this page you can find the example usage for org.apache.commons.lang3.time DateUtils truncate.

Prototype

public static Date truncate(final Object date, final int field) 

Source Link

Document

Truncates a date, leaving the field specified as the most significant field.

For example, if you had the date-time of 28 Mar 2002 13:45:01.231, if you passed with HOUR, it would return 28 Mar 2002 13:00:00.000.

Usage

From source file:org.rippleosi.common.util.DateFormatter.java

public static Date toDateOnly(final String input) {
    Date date = toDate(input);// w ww .ja  v  a 2  s  . co  m
    if (date != null) {
        date = DateUtils.truncate(date, Calendar.DAY_OF_MONTH);

        return date;
    }

    return null;
}

From source file:org.rippleosi.patient.details.search.LegacyPatientSearch.java

private BooleanBuilder generateAdvancedSearchPredicate(PatientQueryParams params) {
    QPatientEntity blueprint = QPatientEntity.patientEntity;
    BooleanBuilder predicate = new BooleanBuilder();

    String nhsNumber = params.getNhsNumber();

    if (nhsNumber != null) {
        predicate.and(blueprint.nhsNumber.eq(nhsNumber));
    } else {//from   ww  w .j a v a  2s .  c om
        String surname = StringUtils.stripToNull(params.getSurname());
        String forename = StringUtils.stripToNull(params.getForename());
        Date dateOfBirth = params.getDateOfBirth();
        String gender = StringUtils.stripToNull(params.getGender());

        if (surname != null) {
            predicate.and(blueprint.lastName.like(surname));
        }
        if (forename != null) {
            predicate.and(blueprint.firstName.like(forename));
        }
        if (dateOfBirth != null) {
            Date truncatedDateOfBirth = DateUtils.truncate(dateOfBirth, Calendar.DATE);

            predicate.and(blueprint.dateOfBirth.eq(truncatedDateOfBirth));
        }
        if (gender != null) {
            predicate.and(blueprint.gender.eq(gender));
        }
    }

    return predicate;
}

From source file:org.sharetask.service.StatisticsServiceImpl.java

private StatisticsDataDTO getStatisticsPerLastHour() {
    Calendar calendar = Calendar.getInstance();
    Date date = DateUtils.truncate(calendar.getTime(), Calendar.HOUR_OF_DAY);
    return new StatisticsDataDTO.Builder().usersCount(userInformationRepository.getCountCreatedAfter(date))
            .workspacesCount(workspaceRepository.getCountCreatedAfter(date))
            .tasksCount(taskRepository.getCountCreatedAfter(date)).build();
}

From source file:org.sharetask.service.StatisticsServiceImpl.java

private StatisticsDataDTO getStatisticsPerLastDay() {
    Calendar calendar = Calendar.getInstance();
    Date date = DateUtils.truncate(calendar.getTime(), Calendar.DATE);
    return new StatisticsDataDTO.Builder().usersCount(userInformationRepository.getCountCreatedAfter(date))
            .workspacesCount(workspaceRepository.getCountCreatedAfter(date))
            .tasksCount(taskRepository.getCountCreatedAfter(date)).build();
}

From source file:org.sharetask.service.StatisticsServiceImpl.java

private StatisticsDataDTO getStatisticsPerLastYear() {
    Calendar calendar = Calendar.getInstance();
    Date date = DateUtils.truncate(calendar.getTime(), Calendar.YEAR);
    return new StatisticsDataDTO.Builder().usersCount(userInformationRepository.getCountCreatedAfter(date))
            .workspacesCount(workspaceRepository.getCountCreatedAfter(date))
            .tasksCount(taskRepository.getCountCreatedAfter(date)).build();
}

From source file:org.sharetask.service.StatisticsServiceImpl.java

private StatisticsDataDTO getStatisticsPerLastWeek() {
    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek());
    Date date = DateUtils.truncate(calendar.getTime(), Calendar.DATE);
    return new StatisticsDataDTO.Builder().usersCount(userInformationRepository.getCountCreatedAfter(date))
            .workspacesCount(workspaceRepository.getCountCreatedAfter(date))
            .tasksCount(taskRepository.getCountCreatedAfter(date)).build();
}

From source file:org.squashtest.tm.service.statistics.campaign.CampaignProgressionStatistics.java

public void computeCumulativeTestPerDate(List<Date> dates) {

    // that where I'd love to have collection.fold(), instead we do the following
    List<Object[]> cumulativeTestsPerDate = new LinkedList<>();

    if (!dates.isEmpty()) {
        // we use here a modified list with a dummy element at the end that will
        // help us to work around a corner case : handling the last element of the loop
        List<Date> trickedDates = new LinkedList<>(dates);
        trickedDates.add(null);/*from   w w w  .  j a  va2 s  .  co m*/

        Iterator<Date> dateIter = trickedDates.iterator();
        Date precDate = dateIter.next();
        Date curDate;
        Date truncated;
        int accumulator = 1;

        // iterate over the rest. Remember that the last element is a dummy null value
        while (dateIter.hasNext()) {
            curDate = dateIter.next();
            if (!isSameDay(precDate, curDate)) {
                truncated = DateUtils.truncate(precDate, Calendar.DATE);
                cumulativeTestsPerDate.add(new Object[] { truncated, accumulator });
            }
            accumulator++;
            precDate = curDate;
        }

    }

    setCumulativeExecutionsPerDate(cumulativeTestsPerDate);

}

From source file:org.wurtele.ifttt.watchers.TrainingScheduleWatcher.java

private void processWordFile(Path path) {
    try {//from   w  w w . jav  a2s  . c om
        XWPFDocument doc = new XWPFDocument(Files.newInputStream(path));
        XWPFWordExtractor extractor = new XWPFWordExtractor(doc);
        List<List<String>> data = new ArrayList<>();
        DateFormat df1 = new SimpleDateFormat("MMM dd, yyyy");
        DateFormat df2 = new SimpleDateFormat("MMM dd, yyyy HH:mm");
        Arrays.asList(extractor.getText().split("\n")).stream().forEach((line) -> {
            try {
                df1.parse(line.split("\t")[0]);
                List<String> list = new ArrayList<>();
                list.addAll(Arrays.asList(line.split("\t")));
                data.add(list);
            } catch (ParseException pe) {
            }
            if (line.startsWith("\t"))
                data.get(data.size() - 1).addAll(Arrays.asList(line.substring(1).split("\t")));
        });
        List<TrainingScheduleEntry> entries = new ArrayList<>();
        for (List<String> event : data) {
            TrainingScheduleEntry entry = new TrainingScheduleEntry();
            entry.setStart(df2.parse(event.get(0) + " " + event.get(1)));
            entry.setEnd(df2.parse(event.get(0) + " " + event.get(2)));
            entry.setGroup(event.get(4));
            entry.setTitle(event.get(5));
            entry.setNotes(event.get(6).length() > 6 ? event.get(6).substring(6) : event.get(6));
            if (event.size() > 13) {
                for (int i = 7; i < 7 + event.size() - 13; i++) {
                    entry.setNotes(entry.getNotes() + " " + event.get(i));
                }
            }
            entry.setInstructor(event.get(event.size() - 6).trim());
            entry.setUniform(event.get(event.size() - 5));
            entry.setLocation(event.get(event.size() - 2));
            entries.add(entry);
        }

        if (!entries.isEmpty()) {
            Collections.sort(entries);

            try (OutputStream os = Files.newOutputStream(processedPath(path));
                    ObjectOutputStream oos = new ObjectOutputStream(os)) {
                oos.writeObject(entries);
            }
            logger.info("Processed " + path);
            Date start = DateUtils.truncate(entries.get(0).getStart(), Calendar.DATE);
            Date end = DateUtils.truncate(entries.get(entries.size() - 1).getEnd(), Calendar.DATE);
            DateFormat df = new SimpleDateFormat("MMM d, yyyy");
            String payload = APNS.newPayload().category("scheduleCategory")
                    .alertTitle("Training Schedule Received")
                    .alertBody(entries.size() + " events found for "
                            + (start.before(end) ? df.format(start) + " - " + df.format(end)
                                    : df.format(start)))
                    .sound("default").customField("schedule", path.getParent().getFileName().toString() + "/"
                            + FilenameUtils.getBaseName(path.getFileName().toString()))
                    .build();
            PushDevices.getDevices().stream().forEach((device) -> {
                PushUtils.getService().push(device, payload);
            });
        }
    } catch (Exception e) {
        logger.error("Failed to process training schedule file: " + path, e);
        FAILED.add(path);
    }
}

From source file:org.wurtele.ifttt.watchers.WorkTimesWatcher.java

private void processFile(Path input) {
    logger.info("Updating " + output);

    try (Workbook wb = new XSSFWorkbook();
            OutputStream out = Files.newOutputStream(output, StandardOpenOption.CREATE,
                    StandardOpenOption.TRUNCATE_EXISTING)) {
        Sheet sheet = wb.createSheet("Time Sheet");
        List<WorkDay> days = new ArrayList<>();
        DateFormat df = new SimpleDateFormat("MMMM dd, yyyy 'at' hh:mma");
        for (String line : Files.readAllLines(input)) {
            String[] data = line.split(";");
            LocationType type = LocationType.valueOf(data[0].toUpperCase());
            Date time = df.parse(data[1]);
            Date day = DateUtils.truncate(time, Calendar.DATE);
            WorkDay wd = new WorkDay(day);
            if (days.contains(wd))
                wd = days.get(days.indexOf(wd));
            else/*from  ww w  .  jav a  2  s  . c om*/
                days.add(wd);
            wd.getTimes().add(new WorkTime(time, type));
        }

        CreationHelper helper = wb.getCreationHelper();
        Font bold = wb.createFont();
        bold.setBoldweight(Font.BOLDWEIGHT_BOLD);

        CellStyle dateStyle = wb.createCellStyle();
        dateStyle.setDataFormat(helper.createDataFormat().getFormat("MMMM d, yyyy"));
        CellStyle timeStyle = wb.createCellStyle();
        timeStyle.setDataFormat(helper.createDataFormat().getFormat("h:mm AM/PM"));
        CellStyle headerStyle = wb.createCellStyle();
        headerStyle.setAlignment(CellStyle.ALIGN_CENTER);
        headerStyle.setFont(bold);
        CellStyle totalStyle = wb.createCellStyle();
        totalStyle.setAlignment(CellStyle.ALIGN_RIGHT);

        Row header = sheet.createRow(0);
        header.createCell(0).setCellValue("DATE");
        header.getCell(0).setCellStyle(headerStyle);

        Collections.sort(days);
        for (int r = 0; r < days.size(); r++) {
            WorkDay day = days.get(r);
            Row row = sheet.createRow(r + 1);
            row.createCell(0).setCellValue(day.getDate());
            row.getCell(0).setCellStyle(dateStyle);
            Collections.sort(day.getTimes());
            for (int c = 0; c < day.getTimes().size(); c++) {
                WorkTime time = day.getTimes().get(c);
                if (sheet.getRow(0).getCell(c + 1) != null
                        && !sheet.getRow(0).getCell(c + 1).getStringCellValue().equals(time.getType().name())) {
                    throw new Exception("Invalid data");
                } else if (sheet.getRow(0).getCell(c + 1) == null) {
                    sheet.getRow(0).createCell(c + 1).setCellValue(time.getType().name());
                    sheet.getRow(0).getCell(c + 1).setCellStyle(headerStyle);
                }
                row.createCell(c + 1).setCellValue(time.getTime());
                row.getCell(c + 1).setCellStyle(timeStyle);
            }
        }

        int totalCol = header.getLastCellNum();
        header.createCell(totalCol).setCellValue("TOTAL");
        header.getCell(totalCol).setCellStyle(headerStyle);

        for (int r = 0; r < days.size(); r++) {
            sheet.getRow(r + 1).createCell(totalCol).setCellValue(days.get(r).getTotal());
            sheet.getRow(r + 1).getCell(totalCol).setCellStyle(totalStyle);
        }

        for (int c = 0; c <= totalCol; c++) {
            sheet.autoSizeColumn(c);
        }

        wb.write(out);
    } catch (Exception e) {
        logger.error("Failed to update " + output, e);
    }
}

From source file:org.zanata.service.impl.ActivityServiceImpl.java

private Date getRoundedTime(Date actionTime) {
    return DateUtils.truncate(actionTime, Calendar.HOUR);
}