Java Code Examples for java.time.ZonedDateTime#minusDays()

The following examples show how to use java.time.ZonedDateTime#minusDays() . 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: TimeUtil.java    From game-server with MIT License 6 votes vote down vote up
/**@
 * 获取与今日相差天数的日期凌晨的毫秒数,负为日期前,正为日期后。如yyyy-MM-dd HH
 *
 * @param days
 * @return
 */
public static long getOffToDayZeroMil(int days) {
    try {
        ZonedDateTime ldt = ZonedDateTime.ofInstant(Instant.ofEpochMilli(currentTimeMillis()), ZoneId.systemDefault());
        if (days < 0) {
            ldt = ldt.minusDays(-days);
        } else {
            ldt = ldt.plusDays(days);
        }
        ldt = ZonedDateTime.of(ldt.getYear(), ldt.getMonthValue(), ldt.getDayOfMonth(), 0, 0, 0, 0, ZoneId.systemDefault());
        return ldt.toInstant().toEpochMilli();
    } catch (Exception e) {
        LOGGER.error("", e);
    }
    return 0;
}
 
Example 2
Source File: ExecutionTimeQuartzWithDayOfYearExtensionIntegrationTest.java    From cron-utils with Apache License 2.0 6 votes vote down vote up
@Test
public void testLastExecutionEveryTwoWeeksStartingWithFirstDayOfYear() {
    final ExecutionTime executionTime = ExecutionTime.forCron(parser.parse(BI_WEEKLY_STARTING_WITH_FIRST_DAY_OF_YEAR));

    for (int i = 1; i < 30; i++) {
        final ZonedDateTime now = ZonedDateTime.of(2017, 10, i, 0, 0, 0, 0, UTC);
        final int dayOfMostRecentPeriod = (now.getDayOfYear() - 1) % 14;
        final ZonedDateTime expected = now.minusDays(dayOfMostRecentPeriod == 0 ? 14 : dayOfMostRecentPeriod);
        final Optional<ZonedDateTime> lastExecution = executionTime.lastExecution(now);
        if (lastExecution.isPresent()) {
            assertEquals("Wrong next time from " + now, expected, lastExecution.get());
        } else {
            fail(LAST_EXECUTION_NOT_PRESENT_ERROR);
        }
    }
}
 
Example 3
Source File: DateTimeWithinPeriodTest.java    From rya with Apache License 2.0 6 votes vote down vote up
@Test
public void testDays() throws DatatypeConfigurationException, ValueExprEvaluationException {
    DatatypeFactory dtf = DatatypeFactory.newInstance();

    ZonedDateTime zTime = testThisTimeDate;
    String time = zTime.format(DateTimeFormatter.ISO_INSTANT);

    ZonedDateTime zTime1 = zTime.minusDays(1);
    String time1 = zTime1.format(DateTimeFormatter.ISO_INSTANT);

    Literal now = VF.createLiteral(dtf.newXMLGregorianCalendar(time));
    Literal nowMinusOne = VF.createLiteral(dtf.newXMLGregorianCalendar(time1));

    DateTimeWithinPeriod func = new DateTimeWithinPeriod();

    assertEquals(TRUE, func.evaluate(VF, now, now, VF.createLiteral(1), OWLTime.DAYS_URI));
    assertEquals(FALSE, func.evaluate(VF, now, nowMinusOne, VF.createLiteral(1), OWLTime.DAYS_URI));
    assertEquals(TRUE, func.evaluate(VF, now, nowMinusOne, VF.createLiteral(2), OWLTime.DAYS_URI));
}
 
Example 4
Source File: TimeUtil.java    From game-server with MIT License 5 votes vote down vote up
public static long offsetCurrentTimeMillis(int offsetDays, int hour, int minute, int secord) {
    ZonedDateTime ldt = ZonedDateTime.ofInstant(Instant.ofEpochMilli(currentTimeMillis()), ZoneId.systemDefault());
    if (offsetDays > 0) {
        ldt = ldt.plusDays(offsetDays);
    } else if (offsetDays < 0) {
        ldt = ldt.minusDays(offsetDays);
    }
    ldt = ldt.withHour(hour);
    ldt = ldt.withMinute(minute);
    ldt = ldt.withSecond(secord);
    return ldt.toEpochSecond() * 1000;
}
 
Example 5
Source File: ReportParams.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public ReportParams(String siteId){
	this.siteId = siteId;
	whatToolIds.add(ReportManager.WHAT_EVENTS_ALLTOOLS);
	// events are counted against a particular date using the server time zone, so initialize the date
	// range based on the current date in that time zone
	ZonedDateTime today = ZonedDateTime.now(ZoneId.systemDefault()).truncatedTo(ChronoUnit.DAYS);
	ZonedDateTime yesterday = today.minusDays(1);
	whenFrom = Date.from(yesterday.toInstant());
	whenTo = Date.from(today.toInstant());
}
 
Example 6
Source File: TimeIterator.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
/**
 * Decrease the given time by {@code units}, which must be positive, of {@code granularity}
 */
public static ZonedDateTime dec(ZonedDateTime time, Granularity granularity, long units) {
  switch (granularity) {
    case MINUTE:
      return time.minusMinutes(units);
    case HOUR:
      return time.minusHours(units);
    case DAY:
      return time.minusDays(units);
    case MONTH:
      return time.minusMonths(units);
  }
  throw new RuntimeException("Unsupported granularity: " + granularity);
}
 
Example 7
Source File: BloodPressureResourceIntTest.java    From 21-points with Apache License 2.0 5 votes vote down vote up
@Test
@Transactional
public void getBloodPressureForLast30Days() throws Exception {
    ZonedDateTime now = ZonedDateTime.now();
    ZonedDateTime twentyNineDaysAgo = now.minusDays(29);
    ZonedDateTime firstDayOfLastMonth = now.withDayOfMonth(1).minusMonths(1);
    createBloodPressureByMonth(twentyNineDaysAgo, firstDayOfLastMonth);

    // create security-aware mockMvc
    restBloodPressureMockMvc = MockMvcBuilders
        .webAppContextSetup(context)
        .apply(springSecurity())
        .build();

    // Get all the blood pressure readings
    restBloodPressureMockMvc.perform(get("/api/blood-pressures")
        .with(user("user").roles("USER")))
        .andExpect(status().isOk())
        .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
        .andExpect(jsonPath("$", hasSize(6)));

    // Get the blood pressure readings for the last 30 days
    restBloodPressureMockMvc.perform(get("/api/bp-by-days/{days}", 30)
        .with(user("user").roles("USER")))
        .andDo(print())
        .andExpect(status().isOk())
        .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
        .andExpect(jsonPath("$.period").value("Last 30 Days"))
        .andExpect(jsonPath("$.readings.[*].systolic").value(hasItem(120)))
        .andExpect(jsonPath("$.readings.[*].diastolic").value(hasItem(69)));
}
 
Example 8
Source File: WeightResourceIntTest.java    From 21-points with Apache License 2.0 5 votes vote down vote up
@Test
@Transactional
public void getForLast30Days() throws Exception {
    ZonedDateTime now = ZonedDateTime.now();
    ZonedDateTime thirtyDaysAgo = now.minusDays(30);
    ZonedDateTime firstDayOfLastMonth = now.withDayOfMonth(1).minusMonths(1);
    createByMonth(thirtyDaysAgo, firstDayOfLastMonth);

    // create security-aware mockMvc
    restWeightMockMvc = MockMvcBuilders
        .webAppContextSetup(context)
        .apply(springSecurity())
        .build();

    // Get all the weighIns
    restWeightMockMvc.perform(get("/api/weights")
        .with(user("user").roles("USER")))
        .andDo(print())
        .andExpect(status().isOk())
        .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
        .andExpect(jsonPath("$", hasSize(6)));

    // Get the weighIns for the last 30 days
    restWeightMockMvc.perform(get("/api/weight-by-days/{days}", 30)
        .with(user("user").roles("USER")))
        .andDo(print())
        .andExpect(status().isOk())
        .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
        .andExpect(jsonPath("$.period").value("Last 30 Days"))
        .andExpect(jsonPath("$.weighIns.[*].weight").value(hasItem(200D)));
}
 
Example 9
Source File: BloodPressureResource.java    From 21-points with Apache License 2.0 5 votes vote down vote up
/**
 * GET  /bp-by-days : get all the blood pressure readings by last x days.
 */
@GetMapping("/bp-by-days/{days}")
@Timed
public ResponseEntity<BloodPressureByPeriod> getByDays(@PathVariable int days) {
    ZonedDateTime rightNow = ZonedDateTime.now(ZoneOffset.UTC);
    ZonedDateTime daysAgo = rightNow.minusDays(days);

    List<BloodPressure> readings =
        bloodPressureRepository.findAllByTimestampBetweenAndUserLoginOrderByTimestampDesc(
            daysAgo, rightNow, SecurityUtils.getCurrentUserLogin().orElse(null));
    BloodPressureByPeriod response = new BloodPressureByPeriod("Last " + days + " Days", readings);
    return new ResponseEntity<>(response, HttpStatus.OK);
}
 
Example 10
Source File: ReportParams.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public ReportParams(String siteId){
	this.siteId = siteId;
	whatToolIds.add(ReportManager.WHAT_EVENTS_ALLTOOLS);
	// events are counted against a particular date using the server time zone, so initialize the date
	// range based on the current date in that time zone
	ZonedDateTime today = ZonedDateTime.now(ZoneId.systemDefault()).truncatedTo(ChronoUnit.DAYS);
	ZonedDateTime yesterday = today.minusDays(1);
	whenFrom = Date.from(yesterday.toInstant());
	whenTo = Date.from(today.toInstant());
}
 
Example 11
Source File: OfflineDataProcessingExecutor.java    From Insights with Apache License 2.0 5 votes vote down vote up
/**
 * 
 * Checks whether query is scheduled to run or not depending on runSchedule
 * and lastRunTime
 * 
 * @param runSchedule
 * @param lastRunTime
 * @return
 */
public Boolean isQueryScheduledToRun(Long runSchedule, String lastRunTime, String cronSchedule) {
	// if lastExecutionTime property is not added in the json file, we'll
	// execute the query by default
	if (lastRunTime == null && (cronSchedule == null || cronSchedule.trim().length() == 0)) {
		return Boolean.TRUE;
	}
	ZonedDateTime dateTime = null;
	ZonedDateTime now = ZonedDateTime.now(InsightsUtils.zoneId);
	Long timeDifferenceInMinutes = null;
	if (lastRunTime != null && !lastRunTime.isEmpty()) {
		dateTime = ZonedDateTime.parse(lastRunTime, formatter);
	}
	if(cronSchedule != null && cronSchedule.trim().length() > 0) {
		try {
			//"0 0 0 1 * ?"
			CronExpression convert = new CronExpressionConverter().convert(cronSchedule);
			if(dateTime == null) {
				dateTime = now.minusDays(1); //If the last run time not present, compare the cron time against last 24 hours.
			}
			Date cronDate = convert.getNextValidTimeAfter(Date.from(dateTime.toInstant()));
			if(cronDate.before(new Date())) {
				return Boolean.TRUE;
			}
		} catch (Exception e) {
			log.error("Unable to parse the CRON expression: "+cronSchedule, e);
		}
	}else {
		if (dateTime != null && now != null) {
			Duration d = Duration.between(dateTime, now);
			timeDifferenceInMinutes = d.abs().toMinutes();
		}
		if (timeDifferenceInMinutes > runSchedule) {
			return Boolean.TRUE;
		}
	}
	return Boolean.FALSE;
}
 
Example 12
Source File: TimeServiceImpl.java    From NoraUi with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public String getDayMinusXBusinessDay(int offsetDay, String zone, String formatter) {
    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(formatter);
    ZonedDateTime date = ZonedDateTime.now(ZoneId.of(zone)).minusDays(offsetDay);
    if ("SATURDAY".equals(date.getDayOfWeek().toString())) {
        date = date.minusDays(1);
    } else if ("SUNDAY".equals(date.getDayOfWeek().toString())) {
        date = date.minusDays(2);
    }
    return date.format(dateTimeFormatter);
}
 
Example 13
Source File: TvMazeUtils.java    From drftpd with GNU General Public License v2.0 4 votes vote down vote up
private static String calculateAge(ZonedDateTime epDate) {
    // Get now
    ZonedDateTime now = ZonedDateTime.now();

    // Get the (positive) time between now and epData
    ZonedDateTime t1 = now;
    ZonedDateTime t2 = epDate;
    if (epDate.isBefore(now)) {
        t1 = epDate;
        t2 = now;
    }

    String age = "";
    long years = ChronoUnit.YEARS.between(t1, t2);
    if (years > 0) {
        age += years+"y";
        t2 = t2.minusYears(years);
    }

    long months = ChronoUnit.MONTHS.between(t1, t2);
    if (months > 0) {
        age += months+"m";
        t2 = t2.minusMonths(months);
    }

    long weeks = ChronoUnit.WEEKS.between(t1, t2);
    if (weeks > 0) {
        age += weeks+"w";
        t2 = t2.minusWeeks(weeks);
    }

    long days = ChronoUnit.DAYS.between(t1, t2);
    if (days > 0) {
        age += days+"d";
        t2 = t2.minusDays(days);
    }
    boolean spaceadded = false;

    long hours = ChronoUnit.HOURS.between(t1, t2);
    if (hours > 0) {
        age += " "+hours+"h";
        spaceadded = true;
        t2 = t2.minusHours(hours);
    }

    long minutes = ChronoUnit.MINUTES.between(t1, t2);
    if (minutes > 0) {
        if (!spaceadded) { age += " ";  }
        age += minutes+"m";
    }
    if (age.length() == 0) { age = "0"; }

    return age;
}
 
Example 14
Source File: AstyanaxTableDAO.java    From emodb with Apache License 2.0 4 votes vote down vote up
@Timed (name = "bv.emodb.table.AstyanaxTableDAO.listUnpublishedDatabusEvents", absolute = true)
@Override
public Iterator<UnpublishedDatabusEvent> listUnpublishedDatabusEvents(Date fromInclusive, Date toExclusive) {
    checkArgument(fromInclusive != null, "fromInclusive date cannot be null");
    checkArgument(toExclusive != null, "toExclusive date cannot be null");

    ZonedDateTime fromInclusiveUTC = fromInclusive.toInstant().atZone(ZoneOffset.UTC).with(ChronoField.MILLI_OF_DAY, 0);
    ZonedDateTime toInclusiveDateUTC = toExclusive.toInstant().atZone(ZoneOffset.UTC).with(ChronoField.MILLI_OF_DAY, 0);
    if (toExclusive.toInstant().equals(toInclusiveDateUTC.toInstant())) {
        toInclusiveDateUTC = toInclusiveDateUTC.minusDays(1);
    }

    // adding 1 to the days to make it inclusive.
    final int inclusiveNumberOfDays = (int) Duration.between(fromInclusiveUTC, toInclusiveDateUTC).toDays() + 1;
    if (inclusiveNumberOfDays > 31) {
        throw new IllegalArgumentException("Specified from and to date range is greater than 30 days which is not supported. Specify a smaller range.");
    }
    List<LocalDate> dates = Stream.iterate(fromInclusiveUTC.toLocalDate(), d -> d.plusDays(1))
            .limit(inclusiveNumberOfDays)
            .collect(Collectors.toList());

    List<UnpublishedDatabusEvent> allUnpublishedDatabusEvents = Lists.newArrayList();
    // using closedOpen which is [a..b) i.e. {x | a <= x < b}
    final Range<Long> requestedRange = Range.closedOpen(fromInclusive.getTime(), toExclusive.getTime());
    for (LocalDate date : dates) {
        String dateKey = date.toString();
        Map<String, Object> recordMap = _backingStore.get(_systemTableUnPublishedDatabusEvents, dateKey, ReadConsistency.STRONG);
        if (recordMap != null) {
            Object tableInfo = recordMap.get("tables");
            if (tableInfo != null) {
                List<UnpublishedDatabusEvent> unpublishedDatabusEvents = JsonHelper.convert(tableInfo, new TypeReference<List<UnpublishedDatabusEvent>>() {});
                // filter events whose time is outside the requestedRange.
                unpublishedDatabusEvents.stream()
                        .filter(unpublishedDatabusEvent -> requestedRange.contains(unpublishedDatabusEvent.getDate().getTime()))
                        .forEach(allUnpublishedDatabusEvents::add);
            }
        }
    }

    return allUnpublishedDatabusEvents.iterator();
}
 
Example 15
Source File: TvMazeUtils.java    From drftpd with GNU General Public License v2.0 4 votes vote down vote up
private static String calculateAge(ZonedDateTime epDate) {
    // Get now
    ZonedDateTime now = ZonedDateTime.now();

    // Get the (positive) time between now and epData
    ZonedDateTime t1 = now;
    ZonedDateTime t2 = epDate;
    if (epDate.isBefore(now)) {
        t1 = epDate;
        t2 = now;
    }

    String age = "";
    long years = ChronoUnit.YEARS.between(t1, t2);
    if (years > 0) {
        age += years+"y";
        t2 = t2.minusYears(years);
    }

    long months = ChronoUnit.MONTHS.between(t1, t2);
    if (months > 0) {
        age += months+"m";
        t2 = t2.minusMonths(months);
    }

    long weeks = ChronoUnit.WEEKS.between(t1, t2);
    if (weeks > 0) {
        age += weeks+"w";
        t2 = t2.minusWeeks(weeks);
    }

    long days = ChronoUnit.DAYS.between(t1, t2);
    if (days > 0) {
        age += days+"d";
        t2 = t2.minusDays(days);
    }
    boolean spaceadded = false;

    long hours = ChronoUnit.HOURS.between(t1, t2);
    if (hours > 0) {
        age += " "+hours+"h";
        spaceadded = true;
        t2 = t2.minusHours(hours);
    }

    long minutes = ChronoUnit.MINUTES.between(t1, t2);
    if (minutes > 0) {
        if (!spaceadded) { age += " ";  }
        age += minutes+"m";
    }
    if (age.length() == 0) { age = "0"; }

    return age;
}
 
Example 16
Source File: InsightsUtils.java    From Insights with Apache License 2.0 4 votes vote down vote up
public static Long getTimeBeforeDaysInSeconds(Long days) {
	ZonedDateTime now = ZonedDateTime.now(zoneId);
	ZonedDateTime after = now.minusDays(days);
	return after.toInstant().getEpochSecond();
}
 
Example 17
Source File: InsightsUtils.java    From Insights with Apache License 2.0 4 votes vote down vote up
public static Long getTimeBeforeDays(Long days) {
	ZonedDateTime now = ZonedDateTime.now(zoneId);
	ZonedDateTime after = now.minusDays(days);
	return after.toInstant().toEpochMilli();
}
 
Example 18
Source File: DeploymentServiceImpl.java    From studio with GNU General Public License v3.0 4 votes vote down vote up
@Override
@ValidateParams
public List<DmDeploymentTaskTO> getDeploymentHistory(@ValidateStringParam(name = "site") String site,
                             @ValidateIntegerParam(name = "daysFromToday") int daysFromToday,
                             @ValidateIntegerParam(name = "numberOfItems") int numberOfItems,
                             @ValidateStringParam(name = "sort") String sort, boolean ascending,
                             @ValidateStringParam(name = "filterType") String filterType) throws SiteNotFoundException {
    // get the filtered list of attempts in a specific date range
    ZonedDateTime toDate = ZonedDateTime.now(ZoneOffset.UTC);
    ZonedDateTime fromDate = toDate.minusDays(daysFromToday);
    List<DeploymentSyncHistory> deployReports = deploymentHistoryProvider.getDeploymentHistory(site,
            getEnvironmentNames(site), fromDate, toDate, dmFilterWrapper, filterType, numberOfItems);
    List<DmDeploymentTaskTO> tasks = new ArrayList<DmDeploymentTaskTO>();

    if (deployReports != null) {
        int count = 0;
        String timezone = servicesConfig.getDefaultTimezone(site);
        //Set<String> processedItems = new HashSet<String>();
        Map<String, Set<String>> processedItems = new HashMap<String, Set<String>>();
        for (int index = 0; index < deployReports.size() && count < numberOfItems; index++) {
            DeploymentSyncHistory entry = deployReports.get(index);
            String env = entry.getEnvironment();
            if (!processedItems.containsKey(env)) {
                processedItems.put(env, new HashSet<String>());
            }
            if (!processedItems.get(env).contains(entry.getPath())) {
                ContentItemTO deployedItem = getDeployedItem(entry.getSite(), entry.getPath());
                if (deployedItem != null) {
                    deployedItem.eventDate = entry.getSyncDate();
                    deployedItem.endpoint = entry.getTarget();
                    deployedItem.setUser(entry.getUser());
                    deployedItem.setEndpoint(entry.getEnvironment());
                    String deployedLabel =
                            entry.getSyncDate().format(DateTimeFormatter.ofPattern(DATE_FORMAT_DEPLOYED));
                    if (tasks.size() > 0) {
                        DmDeploymentTaskTO lastTask = tasks.get(tasks.size() - 1);
                        String lastDeployedLabel = lastTask.getInternalName();
                        if (lastDeployedLabel.equals(deployedLabel)) {
                            // add to the last task if it is deployed on the same day
                            lastTask.setNumOfChildren(lastTask.getNumOfChildren() + 1);
                            lastTask.getChildren().add(deployedItem);
                        } else {
                            tasks.add(createDeploymentTask(deployedLabel, deployedItem));
                        }
                    } else {
                        tasks.add(createDeploymentTask(deployedLabel, deployedItem));
                    }
                    processedItems.get(env).add(entry.getPath());
                }
            }
        }
    }
    return tasks;
}