Java Code Examples for org.apache.commons.lang3.time.DateUtils#addHours()

The following examples show how to use org.apache.commons.lang3.time.DateUtils#addHours() . 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: TodoServiceImpl.java    From appstart with Apache License 2.0 6 votes vote down vote up
@Override
public List<Todo> archive() {
	log.info("Archiving old todos");
	// archive any todos old than 24 hours
	Date today = new Date();
	Date date = DateUtils.addHours(today, -24);
	List<Todo> todos = Todo.findAllToArchive(date);
	
	if(!todos.isEmpty()) {
		for(Todo todo: todos) {
			todo.setArchived(true);
			todo.setDateArchived(today);
		}
		
		Todo.saveAll(todos);
	}
	return todos;
}
 
Example 2
Source File: BIRTDataSet.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
private Date parseStatisticEndDate(String dateString) throws ParseException {
	if (StringUtils.contains(dateString, ":")) {
		return DateUtils.addHours(parseStatisticDate(dateString), 1);
	} else {
		return DateUtils.addDays(parseStatisticDate(dateString), 1);
	}
}
 
Example 3
Source File: FeedUtils.java    From commafeed with Apache License 2.0 5 votes vote down vote up
/**
 * When there was an error fetching the feed
 * 
 */
public static Date buildDisabledUntil(int errorCount) {
	Date now = new Date();
	int retriesBeforeDisable = 3;

	if (errorCount >= retriesBeforeDisable) {
		int disabledHours = errorCount - retriesBeforeDisable + 1;
		disabledHours = Math.min(24 * 7, disabledHours);
		return DateUtils.addHours(now, disabledHours);
	}
	return now;
}
 
Example 4
Source File: TransactionController.java    From hermes with Apache License 2.0 5 votes vote down vote up
/**
 * 获取数据表格
 * 
 * @param name
 * @param beginDate
 * @param endDate
 * @param status
 * @param page
 * @param size
 * @param model
 * @return
 */
@RequestMapping("/table")
public String table(String email, String beginDate, String endDate, String remark, Integer page, Integer size, Model model) {
	try {
		Date sDate = DateUtils.parseDate(beginDate, "yyyy-MM-dd");
		Date eDate = DateUtils.addHours(DateUtils.parseDate(endDate, "yyyy-MM-dd"), 24) ;
		model.addAttribute("rechargeList", transactionService.findRechargeByEmailAndDateBetweenAndRemark(email, sDate, eDate, remark, page, size));
	} catch (Exception e) {
		Logger.error("资金明细:获取数据表格失败");
	}
	
	return "transaction/table";
}
 
Example 5
Source File: CalendarScreen.java    From sample-timesheets with Apache License 2.0 5 votes vote down vote up
protected FactAndPlan[] calculateSummariesByWeeks() {
    Date start = firstDayOfMonth;
    java.util.Calendar javaCalendar = java.util.Calendar.getInstance(userSession.getLocale());
    javaCalendar.setMinimalDaysInFirstWeek(1);
    javaCalendar.setTime(firstDayOfMonth);
    int countOfWeeksInTheMonth = javaCalendar.getActualMaximum(java.util.Calendar.WEEK_OF_MONTH);
    Date lastDayOfMonth = DateUtils.addHours(DateTimeUtils.getLastDayOfMonth(firstDayOfMonth), 23);

    FactAndPlan[] summariesByWeeks = new FactAndPlan[countOfWeeksInTheMonth + 1];
    for (int i = 0; i < countOfWeeksInTheMonth; i++) {
        Date firstDayOfWeek = DateTimeUtils.getFirstDayOfWeek(start);
        Date lastDayOfWeek = DateUtils.addHours(DateTimeUtils.getLastDayOfWeek(start), 23);

        if (firstDayOfWeek.getTime() < firstDayOfMonth.getTime()) {
            firstDayOfWeek = firstDayOfMonth;
        }
        if (lastDayOfWeek.getTime() > lastDayOfMonth.getTime()) {
            lastDayOfWeek = lastDayOfMonth;
        }
        FactAndPlan summaryForTheWeek = new FactAndPlan();
        User currentOrSubstitutedUser = userSession.getCurrentOrSubstitutedUser();
        summaryForTheWeek.fact.setTime(
                validationTools.actualWorkHoursForPeriod(firstDayOfWeek, lastDayOfWeek, currentOrSubstitutedUser)
        );
        summaryForTheWeek.plan.setTime(
                validationTools.workHoursForPeriod(firstDayOfWeek, lastDayOfWeek, currentOrSubstitutedUser)
        );
        summariesByWeeks[i + 1] = summaryForTheWeek;
        start = DateUtils.addWeeks(start, 1);
    }
    return summariesByWeeks;
}
 
Example 6
Source File: OrderServiceImpl.java    From mmall-kay-Java with Apache License 2.0 5 votes vote down vote up
/**
 * 关闭在当前时间hour小时之内未支付订单
 * @param hour
 */
@Override
public void closeOrder(int hour) {
    //获取当前时间hour之前时间
    Date closeTime = DateUtils.addHours(new Date(), -hour);
    String startTime = DateTimeUtil.dateToStr(closeTime);
    List<Order> orderList = orderMapper.selectOrderByStatusAndStartTime(Const.OrderStatusEnum.NO_PAY.getCode(), startTime);
    for (Order order : orderList) {
        List<OrderItem> orderItemList = orderItemMapper.selectByOrderNo(order.getOrderNo());
        for (OrderItem orderItem : orderItemList) {

            //todo 使用写独占锁,一定要用主键where条件,防止锁表。同时必须是支持MySQL的Innodb。
            //获取到对应产品的库存
            Integer productStock = productMapper.selectStockByPrimaryKey(orderItem.getProductId());

            //对应商品已经删除等情况,不做处理
            if (productStock == null) {
                continue;
            }

            //库存数量恢复
            Product product = new Product();
            product.setId(orderItem.getProductId());
            product.setStock(productStock + orderItem.getQuantity());
            int updateCount = productMapper.updateByPrimaryKeySelective(product);
        }
        //更新订单状态,关闭订单
        orderMapper.closeOrderCloseByOrderId(order.getId());
        log.info("关闭订单OrderNo:{}",order.getOrderNo());
    }
}
 
Example 7
Source File: FeedUtils.java    From commafeed with Apache License 2.0 5 votes vote down vote up
/**
 * When the feed was refreshed successfully
 */
public static Date buildDisabledUntil(Date publishedDate, Long averageEntryInterval, Date defaultRefreshInterval) {
	Date now = new Date();

	if (publishedDate == null) {
		// feed with no entries, recheck in 24 hours
		return DateUtils.addHours(now, 24);
	} else if (publishedDate.before(DateUtils.addMonths(now, -1))) {
		// older than a month, recheck in 24 hours
		return DateUtils.addHours(now, 24);
	} else if (publishedDate.before(DateUtils.addDays(now, -14))) {
		// older than two weeks, recheck in 12 hours
		return DateUtils.addHours(now, 12);
	} else if (publishedDate.before(DateUtils.addDays(now, -7))) {
		// older than a week, recheck in 6 hours
		return DateUtils.addHours(now, 6);
	} else if (averageEntryInterval != null) {
		// use average time between entries to decide when to refresh next, divided by factor
		int factor = 2;

		// not more than 6 hours
		long date = Math.min(DateUtils.addHours(now, 6).getTime(), now.getTime() + averageEntryInterval / factor);

		// not less than default refresh interval
		date = Math.max(defaultRefreshInterval.getTime(), date);

		return new Date(date);
	} else {
		// unknown case, recheck in 24 hours
		return DateUtils.addHours(now, 24);
	}
}
 
Example 8
Source File: DateUtil.java    From vjtools with Apache License 2.0 4 votes vote down vote up
/**
 * 加一小时
 */
public static Date addHours(@NotNull final Date date, int amount) {
	return DateUtils.addHours(date, amount);
}
 
Example 9
Source File: DateUtil.java    From vjtools with Apache License 2.0 4 votes vote down vote up
/**
 * 减一小时
 */
public static Date subHours(@NotNull final Date date, int amount) {
	return DateUtils.addHours(date, -amount);
}
 
Example 10
Source File: DateUtil.java    From j360-dubbo-app-all with Apache License 2.0 4 votes vote down vote up
/**
 * 加一小时
 */
public static Date addHours(@NotNull final Date date, int amount) {
	return DateUtils.addHours(date, amount);
}
 
Example 11
Source File: DateUtil.java    From j360-dubbo-app-all with Apache License 2.0 4 votes vote down vote up
/**
 * 减一小时
 */
public static Date subHours(@NotNull final Date date, int amount) {
	return DateUtils.addHours(date, -amount);
}
 
Example 12
Source File: DateUtil.java    From vjtools with Apache License 2.0 4 votes vote down vote up
/**
 * 减一小时
 */
public static Date subHours(@NotNull final Date date, int amount) {
	return DateUtils.addHours(date, -amount);
}
 
Example 13
Source File: EmailerTest.java    From cuba with Apache License 2.0 4 votes vote down vote up
private Date getDeadlineWhichDoesntMatter() {
    return DateUtils.addHours(timeSource.currentTimestamp(), 2);
}
 
Example 14
Source File: TimeUtil.java    From SpringBootUnity with MIT License 4 votes vote down vote up
/**
 * hour小时之前
 */
public static Date hourBefor(int hour) {
    return DateUtils.addHours(new Date(), -hour);
}
 
Example 15
Source File: ComWorkflowValidationService.java    From openemm with GNU Affero General Public License v3.0 4 votes vote down vote up
public boolean isAutoImportHavingShortDeadline(List<WorkflowIcon> icons) {
    WorkflowGraph graph = new WorkflowGraph(icons);

    for (WorkflowIcon icon : icons) {
        if (icon.getType() == WorkflowIconType.IMPORT.getId()) {
            // The deadline icon must always be connected here (an immediate outgoing connection).
            for (WorkflowNode node : graph.getNodeByIcon(icon).getNextNodes()) {
                WorkflowIcon nextIcon = node.getNodeIcon();

                // Make sure that a deadline is at least 1 hours.
                if (nextIcon.getType() == WorkflowIconType.DEADLINE.getId() && nextIcon.isFilled()) {
                    WorkflowDeadline deadline = (WorkflowDeadline) nextIcon;

                    switch (deadline.getDeadlineType()) {
                        case TYPE_DELAY:
                            // Relative deadline: simply check time units and value.
                            switch (deadline.getTimeUnit()) {
                                case TIME_UNIT_MINUTE:
                                    return true;
                                case TIME_UNIT_HOUR:
                                    return deadline.getDelayValue() < WorkflowDeadlineImpl.DEFAULT_AUTOIMPORT_DELAY_LIMIT;
					case TIME_UNIT_DAY:
						break;
					case TIME_UNIT_MONTH:
						break;
					case TIME_UNIT_WEEK:
						break;
					default:
						break;
                            }
                            break;

                        case TYPE_FIXED_DEADLINE:
                            // Absolute deadline: compare to start icon + previous deadline(s).
                            Date minDate = workflowService.getMaxPossibleDate(icon, icons);
                            if (minDate != null) {
                                minDate = DateUtils.addHours(minDate, WorkflowDeadlineImpl.DEFAULT_AUTOIMPORT_DELAY_LIMIT);

                                // Use default timezone here since getMaxPossibleDate uses it as well.
                                Date deadlineDate = WorkflowUtils.mergeIconDateAndTime(deadline.getDate(), deadline.getHour(), deadline.getMinute(), TimeZone.getDefault());

                                if (deadlineDate.before(minDate)) {
                                    return true;
                                }
                            }
                            break;
                            
			default:
				break;
                    }
                }
            }
        }
    }

    return false;
}
 
Example 16
Source File: TestListS3.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Test
public void testListIgnoreByMinAge() throws IOException {
    runner.setProperty(ListS3.REGION, "eu-west-1");
    runner.setProperty(ListS3.BUCKET, "test-bucket");
    runner.setProperty(ListS3.MIN_AGE, "30 sec");

    Date lastModifiedNow = new Date();
    Date lastModifiedMinus1Hour = DateUtils.addHours(lastModifiedNow, -1);
    Date lastModifiedMinus3Hour = DateUtils.addHours(lastModifiedNow, -3);
    ObjectListing objectListing = new ObjectListing();
    S3ObjectSummary objectSummary1 = new S3ObjectSummary();
    objectSummary1.setBucketName("test-bucket");
    objectSummary1.setKey("minus-3hour");
    objectSummary1.setLastModified(lastModifiedMinus3Hour);
    objectListing.getObjectSummaries().add(objectSummary1);
    S3ObjectSummary objectSummary2 = new S3ObjectSummary();
    objectSummary2.setBucketName("test-bucket");
    objectSummary2.setKey("minus-1hour");
    objectSummary2.setLastModified(lastModifiedMinus1Hour);
    objectListing.getObjectSummaries().add(objectSummary2);
    S3ObjectSummary objectSummary3 = new S3ObjectSummary();
    objectSummary3.setBucketName("test-bucket");
    objectSummary3.setKey("now");
    objectSummary3.setLastModified(lastModifiedNow);
    objectListing.getObjectSummaries().add(objectSummary3);
    Mockito.when(mockS3Client.listObjects(Mockito.any(ListObjectsRequest.class))).thenReturn(objectListing);

    Map<String,String> stateMap = new HashMap<>();
    String previousTimestamp = String.valueOf(lastModifiedMinus3Hour.getTime());
    stateMap.put(ListS3.CURRENT_TIMESTAMP, previousTimestamp);
    stateMap.put(ListS3.CURRENT_KEY_PREFIX + "0", "minus-3hour");
    runner.getStateManager().setState(stateMap, Scope.CLUSTER);

    runner.run();

    ArgumentCaptor<ListObjectsRequest> captureRequest = ArgumentCaptor.forClass(ListObjectsRequest.class);
    Mockito.verify(mockS3Client, Mockito.times(1)).listObjects(captureRequest.capture());
    ListObjectsRequest request = captureRequest.getValue();
    assertEquals("test-bucket", request.getBucketName());
    Mockito.verify(mockS3Client, Mockito.never()).listVersions(Mockito.any());

    runner.assertAllFlowFilesTransferred(ListS3.REL_SUCCESS, 1);
    List<MockFlowFile> flowFiles = runner.getFlowFilesForRelationship(ListS3.REL_SUCCESS);
    MockFlowFile ff0 = flowFiles.get(0);
    ff0.assertAttributeEquals("filename", "minus-1hour");
    ff0.assertAttributeEquals("s3.bucket", "test-bucket");
    String lastModifiedTimestamp = String.valueOf(lastModifiedMinus1Hour.getTime());
    ff0.assertAttributeEquals("s3.lastModified", lastModifiedTimestamp);
    runner.getStateManager().assertStateEquals(ListS3.CURRENT_TIMESTAMP, lastModifiedTimestamp, Scope.CLUSTER);
}
 
Example 17
Source File: AddHoursToDate.java    From tutorials with MIT License 4 votes vote down vote up
public Date addHoursWithApacheCommons(Date date, int hours) {
    return DateUtils.addHours(date, hours);
}
 
Example 18
Source File: DataSendEmailJob.java    From feiqu-opensource with Apache License 2.0 4 votes vote down vote up
@Scheduled(cron = "0 0 8 * * ? ")
//    @Scheduled(cron = "0 53 15 * * ? ")
    public void work(){
        
        Stopwatch stopwatch = Stopwatch.createStarted();
        Date now = new Date();
//        DateUtil.offsetDay(now, -1).toString("yyyyMMdd");

        Date begin = DateUtils.addHours(now,-8);
        Date end = DateUtils.addHours(now,-6);

        NginxLogExample example = new NginxLogExample();
        example.createCriteria().andCreateTimeBetween(begin,end).andSpiderTypeEqualTo(0);
        Integer pv = logService.countByExample(example);
        long uv = logService.countUvByExample(example);

        //1 百度爬虫 2 google爬虫 3 bing爬虫 4 搜狗
        example.clear();
        example.createCriteria().andCreateTimeBetween(begin,end)
        .andSpiderTypeEqualTo(1);
        long baiduzhizhu = logService.countByExample(example);
        example.clear();
        example.createCriteria().andCreateTimeBetween(begin,end)
                .andSpiderTypeEqualTo(2);
        long googlezhizhu = logService.countByExample(example);
        example.clear();
        example.createCriteria().andCreateTimeBetween(begin,end)
                .andSpiderTypeEqualTo(3);
        long bingzhizhu = logService.countByExample(example);
        example.clear();
        example.createCriteria().andCreateTimeBetween(begin,end)
                .andSpiderTypeEqualTo(4);
        long sougouzhizhu = logService.countByExample(example);

        String htmlContent = getEmailHtml(DateUtil.offsetDay(now, -1).toString("yyyy-MM-dd")+"的PV UV",pv,uv,baiduzhizhu,
                googlezhizhu,bingzhizhu,sougouzhizhu);
        String yesterday = DateUtil.offsetDay(new Date(), -1).toString("yyyy-MM-dd");
        String prefix = "/home/chenweidong/feiqu/logs";
        File logFile = new File(prefix+"/cwd-web.log."+yesterday);
        File errorlogFile = new File(prefix+"/cwd-web.error.log."+yesterday);
        File gcLogFile = new File(prefix+"/gc.log");
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "GBK");
            helper.setFrom(mailSender.getUsername());
            //邮件主题
            helper.setSubject("社区前一天的PVUV");
            String[] tos = {"***@qq.com","***@qq.com","***@qq.com","***@qq.com"};
            //邮件接收者的邮箱地址
            helper.setTo(tos);
            helper.setText(htmlContent, true);
//            File logFile = new File("D:\\logs\\access_20171113.log");

            if(logFile.exists()){
                helper.addAttachment("logfiles",logFile);
            }
            if(errorlogFile.exists()){
                helper.addAttachment("errorlog",errorlogFile);
            }
            if(gcLogFile.exists()){
                helper.addAttachment("gcLogFile",gcLogFile);
            }
            mailSender.send(mimeMessage);
        } catch (MessagingException e) {
            logger.error("发送邮件失败 ");
        }finally {
            boolean del = logFile.delete();
            if(!del){
                logger.error("删除日志文件失败,{}",logFile.getPath());
            }
            boolean del2 = errorlogFile.delete();
            if(!del2){
                logger.error("删除日志文件失败,{}",errorlogFile.getPath());
            }
            if(gcLogFile.exists()){
                FileUtil.writeBytes(("每天更新\r\n").getBytes(),
                        gcLogFile);
            }
            /*FileUtil.writeBytes((DateUtil.beginOfDay(now).toString() + "每天更新\r\n").getBytes(),
                    new File("/home/tomcat/apache-tomcat-8.5.8/logs/catalina.out"));*/
        }
        stopwatch.stop();
        long seconds = stopwatch.elapsed(TimeUnit.SECONDS);
        logger.info("nginx日志分析发送邮件,耗时{}秒",seconds);
    }
 
Example 19
Source File: DatePlusHours.java    From levelup-java-examples with Apache License 2.0 3 votes vote down vote up
@Test
public void add_hours_to_date_in_java_with_apachecommons () {

	Calendar newYearsEve = Calendar.getInstance();
	newYearsEve.set(2012, 11, 31, 23, 0, 0);
	
	Date newYearsDay = DateUtils.addHours(newYearsEve.getTime(), 1);
	
	SimpleDateFormat dateFormatter = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss z");

	logger.info(dateFormatter.format(newYearsEve.getTime()));
	logger.info(dateFormatter.format(newYearsDay));

	assertTrue(newYearsDay.after(newYearsEve.getTime()));
}
 
Example 20
Source File: DateUtil.java    From feilong-core with Apache License 2.0 2 votes vote down vote up
/**
 * 指定日期 <code>date</code>加减小时.
 * 
 * <h3>说明:</h3>
 * <blockquote>
 * <ol>
 * <li>结果会自动跨月,跨年计算.</li>
 * <li>传入的参数 <code>date</code> 不会改变</li>
 * </ol>
 * </blockquote>
 * 
 * <h3>示例:</h3>
 * 
 * <blockquote>
 * 
 * <pre class="code">
 * DateUtil.addHour(2012-06-29 00:46:24,5)   =2012-06-29 05:46:24
 * DateUtil.addHour(2012-06-29 00:46:24,-5)  =2012-06-28 19:46:24
 * </pre>
 * 
 * </blockquote>
 * 
 * @param date
 *            任意时间
 * @param hour
 *            加减小时数,<span style="color:red">可以是负数</span>,表示前面多少<br>
 * @return 如果 <code>date</code>是null,抛出 {@link java.lang.IllegalArgumentException}<br>
 *         如果 <code>hour==0</code>,那么什么都不做,返回 <code>date</code>,参见 {@link GregorianCalendar#add(int, int)}
 * @throws IllegalArgumentException
 *             如果 <code>date</code> 是<code>null</code>
 * @see org.apache.commons.lang3.time.DateUtils#addHours(Date, int)
 */
public static Date addHour(Date date,int hour){
    return DateUtils.addHours(date, hour);
}