/** 值分布日期格式 */
 private TimeBetween fillWithValueDistriTime(HttpServletRequest request, Model model)
     throws ParseException {
   final String valueDistriDateFormat = "yyyy-MM-dd";
   String valueDistriStartDateParam = request.getParameter("valueDistriStartDate");
   String valueDistriEndDateParam = request.getParameter("valueDistriEndDate");
   Date startDate;
   Date endDate;
   if (StringUtils.isBlank(valueDistriStartDateParam)
       || StringUtils.isBlank(valueDistriEndDateParam)) {
     // 如果为空默认取昨天和今天
     SimpleDateFormat sdf = new SimpleDateFormat(valueDistriDateFormat);
     startDate = sdf.parse(sdf.format(new Date()));
     endDate = DateUtils.addDays(startDate, 1);
     valueDistriStartDateParam = DateUtil.formatDate(startDate, valueDistriDateFormat);
     valueDistriEndDateParam = DateUtil.formatDate(endDate, valueDistriDateFormat);
   } else {
     endDate = DateUtil.parse(valueDistriEndDateParam, valueDistriDateFormat);
     startDate = DateUtil.parse(valueDistriStartDateParam, valueDistriDateFormat);
     // 限制不能超过1天
     if (endDate.getTime() - startDate.getTime() > TimeUnit.DAYS.toMillis(1)) {
       startDate = DateUtils.addDays(endDate, -1);
     }
   }
   // 前端需要
   model.addAttribute("valueDistriStartDate", valueDistriStartDateParam);
   model.addAttribute("valueDistriEndDate", valueDistriEndDateParam);
   // 查询后台需要
   long startTime = NumberUtils.toLong(DateUtil.formatDate(startDate, COLLECT_TIME_FORMAT));
   long endTime = NumberUtils.toLong(DateUtil.formatDate(endDate, COLLECT_TIME_FORMAT));
   return new TimeBetween(startTime, endTime, startDate, endDate);
 }
  private void sendToGoogleCalendar(Utilisateur utilisateur, DemandeAbsence absence, boolean update)
      throws Exception {

    Date dateDebutEvent = absence.getDateDebut();
    if (absence.getDebutPM()) {
      dateDebutEvent = DateUtils.setHours(dateDebutEvent, 14);
    }
    Date dateFinEvent = absence.getDateFin();
    if (absence.getFinAM()) {
      dateFinEvent = DateUtils.setHours(dateFinEvent, 14);
    } else {
      dateFinEvent = DateUtils.addDays(dateFinEvent, 1);
    }

    if (update) {
      String oldTitre = absence.getLibelleType().toString() + "?";
      String titre = absence.getLibelleType().toString();
      calendarService.updateEvent(
          utilisateur.getEmail(), dateDebutEvent, dateFinEvent, oldTitre, titre, "");
    } else {
      String titre = absence.getLibelleType().toString();
      titre += (absence.getStatut().equals(StatutAbsence.VALIDE)) ? "" : "?";
      calendarService.createEvent(utilisateur.getEmail(), dateDebutEvent, dateFinEvent, titre, "");
    }
  }
示例#3
0
  /**
   * 以给定日期为基准展开宏
   *
   * @param str 含有待展开宏的字符串
   * @param dateYmd 基准日期,对应{yyyymmdd},{yyyymmdd-n},{yyyymmdd+n}
   * @return 展开后的字符串
   */
  public static String expandMacroDateYmd(String str, Date dateYmd) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
    Pattern dateYmdPat = Pattern.compile("\\{\\s*yyyymmdd\\s*(([+-])\\s*(\\d+))?\\s*\\}");
    String res = str;
    Matcher matcher = dateYmdPat.matcher(res);
    while (matcher.find()) {
      String expr = matcher.group(1);
      String op = matcher.group(2);
      String ndays = matcher.group(3);

      if (StringUtils.isEmpty(expr)) {
        // 无日期计算部分,直接展开
        res = matcher.replaceFirst(sdf.format(dateYmd));
        matcher = dateYmdPat.matcher(res);
      } else if ("+".equals(op)) {
        // 基准日期+n 天
        int n = Integer.parseInt(ndays);
        res = matcher.replaceFirst(sdf.format(DateUtils.addDays(dateYmd, n)));
        matcher = dateYmdPat.matcher(res);
      } else if ("-".equals(op)) {
        // 基准日期-n 天
        int n = -Integer.parseInt(ndays);
        res = matcher.replaceFirst(sdf.format(DateUtils.addDays(dateYmd, n)));
        matcher = dateYmdPat.matcher(res);
      }
    }
    return res;
  }
  @Before
  public void setUp() {
    rightNow = new Date();
    tenDaysAgo = DateUtils.addDays(rightNow, -10);
    fiveDaysAgo = DateUtils.addDays(rightNow, -5);

    PastSnapshot pastSnapshot = mock(PastSnapshot.class);
    when(pastSnapshot.getIndex()).thenReturn(1);
    when(pastSnapshot.getTargetDate()).thenReturn(fiveDaysAgo);

    PastSnapshot pastSnapshot2 = mock(PastSnapshot.class);
    when(pastSnapshot2.getIndex()).thenReturn(2);
    when(pastSnapshot2.getTargetDate()).thenReturn(tenDaysAgo);

    timeMachineConfiguration = mock(TimeMachineConfiguration.class);
    when(timeMachineConfiguration.getProjectPastSnapshots())
        .thenReturn(Arrays.asList(pastSnapshot, pastSnapshot2));

    context = mock(DecoratorContext.class);
    resource = new File("com/foo/bar");
    when(context.getResource()).thenReturn(resource);

    notificationManager = mock(NotificationManager.class);
    decorator = new NewViolationsDecorator(timeMachineConfiguration, notificationManager);

    rule1 = Rule.create().setRepositoryKey("rule1").setKey("rule1").setName("name1");
    rule2 = Rule.create().setRepositoryKey("rule2").setKey("rule2").setName("name2");
    rule3 = Rule.create().setRepositoryKey("rule3").setKey("rule3").setName("name3");
  }
示例#5
0
  @RequestMapping(value = "/searchActs")
  public String searchActs(HttpServletRequest request, Model model, SearchActForm form) {
    if (null != form
        && StringUtils.isNotEmpty(form.getStartDate())
        && StringUtils.isNotEmpty(form.getEndDate())) {
      try {
        Date startDate = DateUtils.parseDate(form.getStartDate(), new String[] {"yyyy-MM-dd"});
        Date endDate = DateUtils.parseDate(form.getEndDate(), new String[] {"yyyy-MM-dd"});

        PagerManager pager =
            new PagerManager(form.getPageId(), 10, actService.countNewActs(startDate, endDate));
        List<Act> actList =
            actService.searchNewActs(
                startDate, endDate, form.getOrder(), pager.getFirstResult(), pager.getMaxResult());
        List<CmsActView> viewList = new ArrayList<CmsActView>(actList.size());
        for (Act act : actList) {
          viewList.add(
              new CmsActView(
                  act,
                  actService.listSynonymActs(act.getId()),
                  actService.isShieldAct(act.getId())));
        }
        model.addAttribute("cmsActViewList", viewList);
        model.addAttribute("pager", pager);
      } catch (ParseException e) {
        log.error("parse search date error.", e);
      }
      model.addAttribute("searchActForm", form);
    }
    return "cms/act_list";
  }
 private boolean isPeriodeCouranteConges(Date date) {
   Date dateFinPeriodeCourante =
       getDateFinPeriodeConges(DateUtils.truncate(new Date(), Calendar.DATE));
   // ajout d'1 jur car la comparaison des dates doit être <= et la méthode before n'a pas ce
   // comportement par défaut
   return date.before(DateUtils.addSeconds(dateFinPeriodeCourante, 1));
 }
 public static Date changeDate(Date oldDate, LogPseudoTimeChange timeChange)
     throws ParseException {
   Date newDate = null;
   if (timeChange == LogPseudoTimeChange.INCREASE) newDate = DateUtils.addMilliseconds(oldDate, 1);
   else newDate = DateUtils.addMilliseconds(oldDate, -1);
   return newDate;
 }
 protected boolean periodicalIsFullyInPeriod(
     Date periodBeginDate, Date periodEndDate, K periodical) {
   return (periodical.getBeginDate().after(periodBeginDate)
           || DateUtils.isSameDay(periodical.getBeginDate(), periodBeginDate))
       && (periodical.getEndDate().before(periodEndDate)
           || (DateUtils.isSameDay(periodical.getEndDate(), periodEndDate)));
 }
 static {
   try {
     START_DATE = DateUtils.parseDate("01-01-12", new String[] {"dd-MM-yy"});
     END_DATE = DateUtils.addMonths(START_DATE, 1);
   } catch (ParseException e) {
     throw new RuntimeException(e);
   }
 }
示例#10
0
 @Test
 public void testDaysAgo() {
   DateCriterion criterion = new DateCriterion().setDate(3);
   Date date = criterion.getDate();
   assertThat(date.getMinutes(), is(0));
   assertThat(date.getHours(), is(0));
   assertThat(DateUtils.isSameDay(date, DateUtils.addDays(new Date(), -3)), is(true));
 }
示例#11
0
 public boolean isCurrent() {
   Date currentDate = DateUtils.truncate(new Date(), Calendar.DAY_OF_MONTH);
   Date established = DateUtils.truncate(getEstablished(), Calendar.DAY_OF_MONTH);
   Date dueTo = DateUtils.truncate(getDueTo(), Calendar.DAY_OF_MONTH);
   return isActive()
       && ((established.before(currentDate) || established.equals(currentDate))
           && (dueTo.after(currentDate) || dueTo.equals(currentDate)));
 }
示例#12
0
 protected void init() {
   paging = wrapPaging();
   if (to == null) {
     to = new Date(DateUtils.truncate(new Date(), Calendar.DATE).getTime() + 86400000);
   }
   if (from == null) {
     from = DateUtils.addDays(to, -30);
   }
 }
示例#13
0
  /**
   * Get tow dates period as seconds, return -1 if the start or end is null
   *
   * @param start Start date
   * @param end End date
   * @return Period as days or -1
   */
  public static long periodAsSeconds(final Date start, final Date end) {
    if (start == null || end == null) {
      return -1;
    }
    Date truncatedStart = org.apache.commons.lang.time.DateUtils.truncate(start, Calendar.SECOND);
    Date truncatedEnd = org.apache.commons.lang.time.DateUtils.truncate(end, Calendar.SECOND);

    long periodAsMilliSeconds = truncatedEnd.getTime() - truncatedStart.getTime();
    return periodAsMilliSeconds / MILLISECOND_UNIT;
  }
示例#14
0
 @Override //
 public CmsContent getPreCmsContent(Date dateCreated, String site, long id) {
   Date start = DateUtils.addDays(dateCreated, -14);
   Date end = DateUtils.addDays(dateCreated, 1);
   String sql =
       SELECT_FROM
           + " where site = ? and id < ? and date_created between ? and ? order by id desc limit 1";
   return (CmsContent)
       DataAccessUtils.singleResult(
           getSimpleJdbcTemplate().query(sql, getEntityRowMapper(), site, id, start, end));
 }
 @Before
 public void setUp() throws Exception {
   MockitoAnnotations.initMocks(this);
   Date now = DateUtils.truncate(new Date(), Calendar.DATE);
   for (int i = 0; i < 10; i++) {
     messages.add(
         buildMessage(
             DateUtils.addDays(now, i >> 2),
             (i & 1) > 0 ? MessagePriority.HIGH : MessagePriority.LOW));
   }
 }
示例#16
0
 /**
  * This method prepares a view to filter dates between start and end date, sorted by the scheduled
  * date.
  *
  * @param startDate
  * @param endDate
  */
 public void prepareFilterDatesView(java.util.Date startDate, java.util.Date endDate) {
   startDate = DateUtils.addDays(startDate, -1);
   endDate = DateUtils.addDays(endDate, 1);
   java.util.Date scheduleDate = null;
   for (CommitteeScheduleBase committeeSchedule : getSortedCommitteeScheduleList()) {
     scheduleDate = committeeSchedule.getScheduledDate();
     if ((scheduleDate != null) && scheduleDate.after(startDate) && scheduleDate.before(endDate)) {
       committeeSchedule.setFilter(true);
     } else {
       committeeSchedule.setFilter(false);
     }
   }
 }
 public static Date getRangeDate(Date midDate, int unitRange, TsUnit aTsUnit, int addOrSub) {
   Date result = null;
   if (aTsUnit == TsUnit.YEARLY) {
     result = DateUtils.addYears(midDate, unitRange * addOrSub);
   } else if (aTsUnit == TsUnit.DAILY) {
     result = DateUtils.addDays(midDate, unitRange * addOrSub);
   } else if (aTsUnit == TsUnit.MONTHLY) {
     result = DateUtils.addMonths(midDate, unitRange * addOrSub);
   } else {
     EUtils.throwNotSupportedException(Version.V1_0_0);
   }
   return result;
 }
 @Override
 public String getIndexResult(String[] brands, Date date) {
   if (date != null) {
     DayStatus ds = dataDaoV2.getDayStatus(date);
     if (ds == null || ds.getStatus() == null || ds.getStatus() == 0) {
       SimpleDateFormat sdf = new SimpleDateFormat("MM月dd日");
       return this.getErrorResult(3002, sdf.format(date) + "没有相关数据,请重新选择日期");
     }
   }
   Date yesterday = getYesterday(date);
   Set<String> bSet = new HashSet<String>();
   for (String brand : brands) {
     bSet.add(brand);
   }
   List<BrandResult> indexBrandResults = dataDaoV2.getBrandResult(yesterday, brands);
   for (BrandResult ibr : indexBrandResults) {
     if (springProperty.isMockValue()) {
       ibr.setDayAmount(10000L);
     }
     bSet.remove(ibr.getBrand());
   }
   for (String brand : bSet) {
     BrandResult ibr = new BrandResult(brand, "", 0);
     indexBrandResults.add(ibr);
   }
   IndexStatResult ir = new IndexStatResult();
   ir.setBrands(indexBrandResults);
   ir.setResult(0);
   ir.setDate(yesterday);
   ir.setClientVersion(springProperty.getClientVersion());
   Date realYesterday =
       DateUtils.addDays(DateUtils.truncate(new Date(), Calendar.DAY_OF_MONTH), -1);
   DayStatus ds = dataDaoV2.getDayStatus(realYesterday);
   if (ds != null && ds.getStatus() != null && ds.getStatus().intValue() != 0) {
     ir.setYesterday(true);
   } else {
     ir.setYesterday(false);
   }
   List<Date> availableDates = dataDaoV2.getAvailableDates(realYesterday);
   List<String> ads = new ArrayList<String>();
   SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
   for (Date ad : availableDates) {
     ads.add(sdf.format(ad));
   }
   ir.setAvailableDates(ads);
   JsonConfig jsonConfig = new JsonConfig();
   jsonConfig.registerJsonValueProcessor(Date.class, new DateJsonValueProcessor("yyyy-MM-dd"));
   jsonConfig.registerJsonValueProcessor(Integer.class, new IntegerJsonValueProcessor());
   String result = JSONObject.fromObject(ir, jsonConfig).toString();
   return result;
 }
示例#19
0
 public String getHolidayListJSON(Date beginDate, Date endDate) {
   final JsonArrayNodeBuilder result = anArrayBuilder();
   // т.к. отпуска могут начинаться ранее или позднее заданных дат, то на всякий случай прибавим к
   // диапазону
   // по месяцу с обоих концов
   List<Holiday> holidays =
       calendarService.getHolidaysForRegion(
           DateUtils.addDays(beginDate, -30), DateUtils.addDays(endDate, 30), null);
   for (Holiday holiday : holidays) {
     result.withElement(
         aStringBuilder(dateToString(holiday.getCalDate().getCalDate(), VIEW_DATE_PATTERN)));
   }
   return JsonUtil.format(result);
 }
示例#20
0
  public static Date getGuDongDate(String str) {
    str = StringUtils.replace(str, " ", "");
    str = StringUtils.replace(str, "十五", "15");
    str = StringUtils.replace(str, "3月中旬", "3月15日");
    str = StringUtils.replace(str, "2月十五日", "2月15日");
    str = StringUtils.replace(str, "2月中旬", "2月15日");
    str = StringUtils.replace(str, "一月29日", "1月29日");
    str = StringUtils.replace(str, "1月末", "1月29日");
    str = StringUtils.replace(str, "2.29", "2月29日");

    {
      Pattern pattern = Pattern.compile("[0-9]{4}年[0-9]{1,}月[0-9]{1,}日");
      Matcher matcher = pattern.matcher(str);
      String value = "";

      while (matcher.find()) {
        value = (matcher.group());
      }
      // System.out.println("value:"+value);
      if (StringUtils.isNotBlank(value)) {
        String patterns[] = new String[] {"yyyy年M月d日"};
        try {
          Date date = (DateUtils.parseDate(value, patterns));
          return date;
        } catch (ParseException e) {
          e.printStackTrace();
        }
      }
    }

    {
      Pattern pattern = Pattern.compile("([0-9]{1,}月[0-9]{1,}日)");
      Matcher matcher = pattern.matcher(str);
      String value = "";
      while (matcher.find()) {
        value = (matcher.group());
      }
      // System.out.println("value222:"+value);
      if (StringUtils.isNotBlank(value)) {
        String patterns[] = new String[] {"M月d日"};
        try {
          Date date = (DateUtils.parseDate(value, patterns));
          return DateUtils.setYears(date, 2016);
        } catch (ParseException e) {
          e.printStackTrace();
        }
      }
    }
    return null;
  }
示例#21
0
  private void createOperations(Date startDate, int numberOfDays, Context context) {
    for (int i = 0; i < numberOfDays; i++) {
      Date date = DateUtils.addDays(startDate, i);

      if (i % 7 == 0) {
        income(date, context.accounts.get(0), context.salaryCategory, new BigDecimal("16000"));
      }
      if (i % 5 == 0) {
        income(
            date,
            context.accounts.get(1),
            context.otherIncomeCategory,
            new BigDecimal(1000 + Math.round(Math.random() * 5000)));
      }

      for (int j = 0; j < Math.random() * 7; j++) {
        expense(date, context.accounts.get(1), context);
        if (j % 2 == 0) expense(date, context.accounts.get(0), context);
      }

      if (i % 2 == 0) {
        Account account2 =
            context.accounts.get((int) (1 + Math.random() * (context.accounts.size() - 1)));
        transfer(date, context.accounts.get(0), account2);
      }
    }
  }
示例#22
0
  public static CoveringInfo getWeeklyCoveringInfo(Date from, Date to) {
    int dayDiff = 0;
    Date tmpFrom = from;
    while (tmpFrom.before(to)) {
      tmpFrom = DateUtils.addDays(tmpFrom, 1);
      dayDiff++;
    }

    if (dayDiff < 7) {
      return new CoveringInfo(0, false);
    }

    Calendar cal = Calendar.getInstance();
    cal.setTime(from);
    int fromWeek = cal.get(Calendar.WEEK_OF_YEAR);
    int fromDay = cal.get(Calendar.DAY_OF_WEEK);
    int fromYear = cal.get(YEAR);

    cal.clear();
    cal.set(YEAR, fromYear);
    cal.set(Calendar.WEEK_OF_YEAR, fromWeek);
    cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
    int maxDayInWeek = cal.getActualMaximum(Calendar.DAY_OF_WEEK);
    Date fromWeekStartDate = cal.getTime();
    boolean coverable = dayDiff % 7 == 0;
    if (fromWeekStartDate.before(from)) {
      // Count from the start of next week
      dayDiff -= (maxDayInWeek - (fromDay - Calendar.SUNDAY));
      coverable = false;
    }

    return new CoveringInfo(dayDiff / 7, coverable);
  }
  public String getBeforeHeartBeatTime() {

    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date date = new Date();
    String result = formatter.format(DateUtils.addSeconds(date, -31));
    return result;
  }
示例#24
0
 public static Date parseDate(String date, String customDateFormat) {
   try {
     return DateUtils.parseDate(date, (new String[] {customDateFormat}));
   } catch (ParseException pe) {
     return null;
   }
 }
示例#25
0
 public static Date parseDate(String date) {
   try {
     return DateUtils.parseDate(date, datePatterns);
   } catch (ParseException pe) {
     return null;
   }
 }
 /**
  * Method generates a date object base on the daysShift param.
  *
  * @param daysShift 0 means now, 7 means (now, -7 days)
  * @return date object
  */
 private Date getDateForQuery(int daysShift) {
   Date queryDate = new Date();
   if (daysShift > 0) {
     queryDate = DateUtils.addDays(queryDate, -daysShift);
   }
   return queryDate;
 }
 private Date getCalendarDate(Date date, int calendar) {
   Calendar cal = Calendar.getInstance();
   cal.setTime(date);
   if (calendar == Calendar.WEEK_OF_MONTH) {
     while (cal.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
       cal.add(Calendar.DAY_OF_MONTH, -1);
     }
     return cal.getTime();
   } else if (calendar == Calendar.MONTH) {
     return DateUtils.truncate(cal, Calendar.MONTH).getTime();
   } else if (calendar == Calendar.YEAR) {
     return DateUtils.truncate(cal, Calendar.YEAR).getTime();
   } else {
     return null;
   }
 }
示例#28
0
 protected Date createDate(String date) {
   try {
     return DateUtils.parseDate(date, dt_formats);
   } catch (ParseException e) {
     throw new RuntimeException(e);
   }
 }
示例#29
0
  @RequestMapping(value = "/addDemo1")
  public ModelAndView addDemo1(
      @RequestParam("name") String name,
      @RequestParam("passowrd") String passowrd,
      @RequestParam("email") String email,
      @RequestParam("createDate") String createDate) {
    ModelAndView mv = new ModelAndView();

    Demo demo = new Demo();
    demo.setName(name);
    demo.setPassowrd(passowrd);
    demo.setEmail(email);
    Date createDateInfo = null;
    try {
      createDateInfo =
          DateUtils.parseDate(createDate, new String[] {"yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd"});
    } catch (ParseException e) {
      createDateInfo = new Date();
    }
    demo.setCreateDate(createDateInfo);

    this.demoService.insertDemo(demo);

    mv.setViewName("demo/addSuccess");
    mv.addObject("resFlag", "success");
    return mv;
  }
  public String getBeforeTime() {

    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date date = new Date();
    String result = formatter.format(DateUtils.addMinutes(date, -3));
    return result;
  }