Java 类org.apache.commons.lang3.time.DateFormatUtils 实例源码

项目:solo-spring    文件:AbstractFreeMarkerRenderer.java   
/**
     * Processes the specified FreeMarker template with the specified request,
     * data model.
     *
     * @param request
     *            the specified request
     * @param dataModel
     *            the specified data model
     * @param template
     *            the specified FreeMarker template
     * @return generated HTML
     * @throws Exception
     *             exception
     */
    protected String genHTML(final HttpServletRequest request, final Map<String, Object> dataModel,
            final Template template) throws Exception {
        final StringWriter stringWriter = new StringWriter();

        template.setOutputEncoding("UTF-8");
        template.process(dataModel, stringWriter);

        final StringBuilder pageContentBuilder = new StringBuilder(stringWriter.toString());

        final long endimeMillis = System.currentTimeMillis();
        final String dateString = DateFormatUtils.format(endimeMillis, "yyyy/MM/dd HH:mm:ss");
//      final long startTimeMillis = (Long) request.getAttribute(Keys.HttpRequest.START_TIME_MILLIS);
        final long startTimeMillis = System.currentTimeMillis();
        final String msg = String.format("<!-- Generated by B3log Latke(%1$d ms), %2$s -->",
                endimeMillis - startTimeMillis, dateString);

        pageContentBuilder.append(msg);

        return pageContentBuilder.toString();
    }
项目:solo-spring    文件:SitemapProcessor.java   
/**
 * Adds archives (archive-articles) into the specified sitemap.
 * 
 * @param sitemap
 *            the specified sitemap
 * @throws Exception
 *             exception
 */
private void addArchives(final Sitemap sitemap) throws Exception {
    final JSONObject result = archiveDateDao.get(new Query());
    final JSONArray archiveDates = result.getJSONArray(Keys.RESULTS);

    for (int i = 0; i < archiveDates.length(); i++) {
        final JSONObject archiveDate = archiveDates.getJSONObject(i);
        final long time = archiveDate.getLong(ArchiveDate.ARCHIVE_TIME);
        final String dateString = DateFormatUtils.format(time, "yyyy/MM");

        final URL url = new URL();

        url.setLoc(Latkes.getServePath() + "/archives/" + dateString);

        sitemap.addURL(url);
    }
}
项目:solo-spring    文件:ArticleMgmtService.java   
/**
 * Gets article permalink for adding article with the specified article.
 *
 * @param article
 *            the specified article
 * @return permalink
 * @throws ServiceException
 *             if invalid permalink occurs
 */
private String getPermalinkForAddArticle(final JSONObject article) throws ServiceException {
    final Date date = (Date) article.opt(Article.ARTICLE_CREATE_DATE);

    String ret = article.optString(Article.ARTICLE_PERMALINK);

    if (StringUtils.isBlank(ret)) {
        ret = "/articles/" + DateFormatUtils.format(date, "yyyy/MM/dd") + "/" + article.optString(Keys.OBJECT_ID)
                + ".html";
    }

    if (!ret.startsWith("/")) {
        ret = "/" + ret;
    }

    if (PermalinkQueryService.invalidArticlePermalinkFormat(ret)) {
        throw new ServiceException(langPropsService.get("invalidPermalinkFormatLabel"));
    }

    if (permalinkQueryService.exist(ret)) {
        throw new ServiceException(langPropsService.get("duplicatedPermalinkLabel"));
    }

    return ret.replaceAll(" ", "-");
}
项目:qfii-tracker    文件:ConnectParser.java   
private void parseAndUpdate(Date queryDate, String directory, PostgreStorage storage,
    String market)
    throws IOException, ParseException {
  List<StockShareholding> stockShareholdings = parse(queryDate, directory);
  if (!stockShareholdings.isEmpty()) {
    if (stockShareholdings.get(0).getDate().equals(queryDate)) {
      storage.saveShareholdings(stockShareholdings, market);
      logger.info("Market {} date {} data has been parsed and updated", market,
          DateFormatUtils.format(queryDate, "yyyy-MM-dd"));
    } else {
      logger.warn("Market {} date {} data in an inconsistent state, operation skipped", market,
          DateFormatUtils.format(queryDate, "yyyy-MM-dd"));
    }
  } else {
    logger.info("Market {} date {} data not existed, operation skipped", market,
        DateFormatUtils.format(queryDate, "yyyy-MM-dd"));
  }
}
项目:datax    文件:ColumnCast.java   
static String asString(final DateColumn column) {
    if (null == column.asDate()) {
        return null;
    }

    switch (column.getSubType()) {
    case DATE:
        return DateFormatUtils.format(column.asDate(), DateCast.dateFormat,
                DateCast.timeZoner);
    case TIME:
        return DateFormatUtils.format(column.asDate(), DateCast.timeFormat,
                DateCast.timeZoner);
    case DATETIME:
        return DateFormatUtils.format(column.asDate(),
                DateCast.datetimeFormat, DateCast.timeZoner);
    default:
        throw DataXException
                .asDataXException(CommonErrorCode.CONVERT_NOT_SUPPORT,
                        "时间类型出现不支持类型,目前仅支持DATE/TIME/DATETIME。该类型属于编程错误,请反馈给DataX开发团队 .");
    }
}
项目:configcenter    文件:CacheFileHandler.java   
/**
 * 缓存配置
 */
public void storeConfig(Map<String, String> properties) {
    try {
        // 如果缓存文件不存在,则创建
        FileUtils.createFileIfAbsent(cacheFile.getPath());
        OutputStream out = null;
        try {
            out = new FileOutputStream(cacheFile);
            mapToProps(properties).store(out, "updated at " + DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        } finally {
            if (out != null) {
                out.close();
            }
        }
    } catch (IOException e) {
        ExceptionUtils.rethrow(e);
    }
}
项目:rexxar    文件:RexxarDateUtils.java   
/** 
 * @Title:getMonthFirstDay 
 * @Description: 得到当前月的第一天. 
 * @return 
 * @return String 
 */  
public static String getMonthFirstDay() {  
    Calendar cal = Calendar.getInstance();  
    // 方法一,默认只设置到年和月份.  
    // Calendar f = (Calendar) cal.clone();  
    // f.clear();  
    // f.set(Calendar.YEAR, cal.get(Calendar.YEAR));  
    // f.set(Calendar.MONTH, cal.get(Calendar.MONTH));  
    // f.set(Calendar.DAY_OF_MONTH, cal.getActualMinimum(Calendar.DATE));  
    // return DateFormatUtils.format(f, DATE_FORMAT);  

    // 方法二.  
    cal.set(Calendar.DATE, 1);  
    return DateFormatUtils.format(cal, DATE_FORMAT);  

}
项目:rexxar    文件:RexxarDateUtils.java   
/** 
 * @Title:getMonthLastDay 
 * @Description: 得到当前月最后一天 
 * @return 
 * @return String 
 */  
public static String getMonthLastDay() {  
    Calendar cal = Calendar.getInstance();  
    Calendar f = (Calendar) cal.clone();  
    f.clear();  
    // 方法一  
    // f.set(Calendar.YEAR, cal.get(Calendar.YEAR));  
    // f.set(Calendar.MONTH, cal.get(Calendar.MONTH) + 1);  
    // f.set(Calendar.MILLISECOND, -1);  
    // return DateFormatUtils.format(f, DATE_FORMAT);  

    // 方法二  
    // f.set(Calendar.YEAR, cal.get(Calendar.YEAR));  
    // f.set(Calendar.MONTH, cal.get(Calendar.MONTH));  
    // f.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DATE));  
    // return DateFormatUtils.format(f, DATE_FORMAT);  

    // 方法三(同一)  
    cal.set(Calendar.DATE, 1);// 设为当前月的1号  
    cal.add(Calendar.MONTH, 1);// 加一个月,变为下月的1号  
    cal.add(Calendar.DATE, -1);// 减去一天,变为当月最后一天  
    return DateFormatUtils.format(cal, DATE_FORMAT);  
}
项目:rexxar    文件:RexxarDateUtils.java   
/** 
 * @Title:getPreviousMonthFirst 
 * @Description: 得到上个月的第一天 
 * @return 
 * @return String 
 */  
public static String getPreviousMonthFirst() {  
    Calendar cal = Calendar.getInstance();  
    Calendar f = (Calendar) cal.clone();  
    f.clear();  
    // 方法一  
    // f.set(Calendar.YEAR, cal.get(Calendar.YEAR));  
    // f.set(Calendar.MONTH, cal.get(Calendar.MONTH) - 1);  
    // f.set(Calendar.DATE, 1);  
    // return DateFormatUtils.format(f, DATE_FORMAT);  

    // 方法二  
    // f.set(Calendar.YEAR, cal.get(Calendar.YEAR));  
    // f.set(Calendar.MONTH, cal.get(Calendar.MONTH) - 1);  
    // f.set(Calendar.DAY_OF_MONTH, cal.getActualMinimum(Calendar.DATE));  
    // return DateFormatUtils.format(f, DATE_FORMAT);  

    // 方法三(同一)  
    cal.set(Calendar.DATE, 1);// 设为当前月的1号  
    cal.add(Calendar.MONTH, -1);  
    return DateFormatUtils.format(cal, DATE_FORMAT);  
}
项目:rexxar    文件:RexxarDateUtils.java   
/** 
 * @Title:getPreviousMonthEnd 
 * @Description: 得到上个月最后一天 
 * @return 
 * @return String 
 */  
public static String getPreviousMonthEnd() {  
    Calendar cal = Calendar.getInstance();  
    Calendar f = (Calendar) cal.clone();  
    f.clear();  
    // 方法一  
    // f.set(Calendar.YEAR, cal.get(Calendar.YEAR));  
    // f.set(Calendar.MONTH, cal.get(Calendar.MONTH));  
    // f.set(Calendar.MILLISECOND, -1);  
    // return DateFormatUtils.format(f, DATE_FORMAT);  

    // 方法二  
    // f.set(Calendar.YEAR, cal.get(Calendar.YEAR));  
    // f.set(Calendar.MONTH, cal.get(Calendar.MONTH) - 1);  
    // f.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DATE));  
    // return DateFormatUtils.format(f, DATE_FORMAT);  

    // 方法三(同一)  
    cal.set(Calendar.DATE, 1);// 设为当前月的1号  
    cal.add(Calendar.MONTH, 0);//  
    cal.add(Calendar.DATE, -1);// 减去一天,变为当月最后一天  
    return DateFormatUtils.format(cal, DATE_FORMAT);  
}
项目:rexxar    文件:RexxarDateUtils.java   
/** 
 * @Title:getNextMonthFirst 
 * @Description: 得到下个月的第一天 
 * @return 
 * @return String 
 */  
public static String getNextMonthFirst() {  
    Calendar cal = Calendar.getInstance();  
    Calendar f = (Calendar) cal.clone();  
    f.clear();  
    // 方法一  
    // f.set(Calendar.YEAR, cal.get(Calendar.YEAR));  
    // f.set(Calendar.MONTH, cal.get(Calendar.MONTH) + 1);  
    // f.set(Calendar.DATE, 1);  
    // or f.set(Calendar.DAY_OF_MONTH,cal.getActualMinimum(Calendar.DATE));  
    // return DateFormatUtils.format(f, DATE_FORMAT);  

    // 方法二  
    cal.set(Calendar.DATE, 1);// 设为当前月的1号  
    cal.add(Calendar.MONTH, +1);// 加一个月,变为下月的1号  
    return DateFormatUtils.format(cal, DATE_FORMAT);  
}
项目:rexxar    文件:RexxarDateUtils.java   
/** 
 * @Title:getDaysListBetweenDates 
 * @Description: 获得两个日期之间的连续日期. 
 * @param begin 
 *            开始日期 . 
 * @param end 
 *            结束日期 . 
 * @return 
 * @return List<String> 
 */  
public static List<String> getDaysListBetweenDates(String begin, String end) {  
    List<String> dateList = new ArrayList<String>();  
    Date d1;  
    Date d2;  
    try {  
        d1 = DateUtils.parseDate(begin, DATE_FORMAT);  
        d2 = DateUtils.parseDate(end, DATE_FORMAT);  
        if (d1.compareTo(d2) > 0) {  
            return dateList;  
        }  
        do {  
            dateList.add(DateFormatUtils.format(d1, DATE_FORMAT));  
            d1 = DateUtils.addDays(d1, 1);  
        } while (d1.compareTo(d2) <= 0);  
    } catch (ParseException e) {  
        e.printStackTrace();  
    }  
    return dateList;  
}
项目:rexxar    文件:RexxarDateUtils.java   
/** 
 * @Title:getMonthsListBetweenDates 
 * @Description: 获得连续的月份 
 * @param begin 
 * @param end 
 * @return 
 * @return List<String> 
 */  
public static List<String> getMonthsListBetweenDates(String begin, String end) {  
    List<String> dateList = new ArrayList<String>();  
    Date d1;  
    Date d2;  
    try {  
        d1 = DateUtils.parseDate(begin, DATE_FORMAT);  
        d2 = DateUtils.parseDate(end, DATE_FORMAT);  
        if (d1.compareTo(d2) > 0) {  
            return dateList;  
        }  
        do {  
            dateList.add(DateFormatUtils.format(d1, MONTH_FORMAT));  
            d1 = DateUtils.addMonths(d1, 1);  
        } while (d1.compareTo(d2) <= 0);  
    } catch (ParseException e) {  
        e.printStackTrace();  
    }  
    return dateList;  
}
项目:garoon-google    文件:Span.java   
@Override
public String toString() {
    StringBuilder builder = new StringBuilder();
    builder.append("[");
    if( this.start == null )
        builder.append("start=null");
    else
        builder.append("start="+DateFormatUtils.ISO_DATETIME_FORMAT.format(this.start));
    builder.append(", ");
    if( this.end == null )
        builder.append("end=null");
    else
        builder.append("end="+DateFormatUtils.ISO_DATETIME_FORMAT.format(this.end));
    builder.append("]");
    return builder.toString();
}
项目:java-cme-mdp3-handler    文件:MBOWithMBPMain.java   
@Override
public int onSecurityDefinition(final String channelId, final MdpMessage mdpMessage) {
    SbeString secGroup = SbeString.allocate(10);
    mdpMessage.getString(1151, secGroup);
    int securityID = mdpMessage.getInt32(48);
    short marketSegmentID = mdpMessage.getUInt8(1300);
    double strikePrice = 0;
    if(mdpMessage.hasField(202)) {
        strikePrice = mdpMessage.getInt64(202) * Math.pow(10, -7);
    }
    String securityGroup = secGroup.getString();
    MdpGroup mdpGroup = SbeGroup.instance();
    mdpMessage.getGroup(864, mdpGroup);
    MdpGroupEntry mdpGroupEntry = SbeGroupEntry.instance();

    logger.info("Received SecurityDefinition(d). securityID '{}', ChannelId: {}, Schema Id: {}, securityGroup '{}', marketSegmentID '{}', strikePrice '{}'", securityID, channelId, mdpMessage.getSchemaId(), securityGroup, marketSegmentID, strikePrice);
    while (mdpGroup.hashNext()){
        mdpGroup.next();
        mdpGroup.getEntry(mdpGroupEntry);
        long eventTime = mdpGroupEntry.getUInt64(1145);
        short eventType = mdpGroupEntry.getUInt8(865);
        logger.info("eventTime - '{}'({}), eventType - '{}'", DateFormatUtils.format(eventTime/1000000, "yyyyMMdd HHmm", TimeZone.getTimeZone("UTC")), eventTime, eventType);
    }
    return MdEventFlags.MESSAGE;
}
项目:mohoo-wechat-pay    文件:WXPayTest.java   
public void WXPayInit() {
    // 读取 resources 文件
    String filePath = System.getProperty("user.dir") + "/rootca.pem";
    WXPay.initSDKConfiguration("YIyqXSZ37xWFsIVDJ86V2uUL1Ly0Gz80", "wxae6a7f991c35cb0d", "1307253101", "", filePath,
            "1307253101");
    System.out.println("CertLocalPath:" + filePath);
    System.out.println(RandomStringUtils.randomNumeric(32));
    ScanPayReqData scanPayReqData = new ScanPayReqData("123123123", "商品测试", "attach",
            RandomStringUtils.randomNumeric(32), 1, "test", "127.0.0.1",
            DateFormatUtils.format(new Date(), "yyyyMMddHHmmss"),
            DateFormatUtils.format(new Date(), "yyyyMMddHHmmss"), "test");
    try {
        String info = WXPay.requestScanPayService(scanPayReqData);
        System.out.println(info);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    Assert.assertNotNull(WXPay.class);
}
项目:meazza    文件:URLUtils.java   
/**
 * 查询字符串后面增加参数
 *
 * @param queryString
 *            查询字符串,比如:id=1&type=1
 * @param name
 *            参数的名称
 * @param value
 *            参数的值
 * @return 拼接后的查询字符串
 */
private static StringBuilder appendParameter(StringBuilder queryString, String name, Object value) {
    queryString.append(name);
    queryString.append(EQUALS_SIGN);

    if (value instanceof Boolean) {
        value = ((Boolean) value).booleanValue() ? "1" : "0";
    } else if (value instanceof Date) {
        value = DateFormatUtils.ISO_DATE_FORMAT.format((Date) value);
    }

    try {
        queryString.append(URLEncoder.encode(String.valueOf(value), charSet));
    } catch (UnsupportedEncodingException e) {
        // ignore
    }
    return queryString;
}
项目:MyBatisPioneer    文件:FileHandler.java   
public static String backup(String origFileName) throws IOException {

        // Get backup file name by inserting timestamp before extension name.
        String timestamp = DateFormatUtils.format(Calendar.getInstance().getTime(), "[yyyy.MM.dd'T'HH.mm.ss]");
        int lastIdxOfDot = origFileName.lastIndexOf(".");
        String backupFileName = origFileName.substring(0, lastIdxOfDot + 1) + timestamp + origFileName.substring(lastIdxOfDot, origFileName.length());

        // Create backup file by renaming original file.
        File origFile = new File(origFileName);
        File backFile = new File(backupFileName);

        logger.info("BACKUP: Begin to make a backup for file: " + origFileName);
        FileUtils.copyFile(origFile, backFile);

        return backupFileName;

    }
项目:excel-bean    文件:BeanUtilsTest.java   
@Test
public void testMap2Bean() {
    profiler.start("testMap2Bean");
    String date = "2016.10.23/12:29:56";
    Map<String, String> map = new LinkedHashMap<String, String>();
    map.put("姓名", "张三");
    map.put("年龄", "18");
    map.put("生日", date);
    map.put("语文分数", "99.3");
    map.put("数学分数", "89.34");
    map.put("性别", "女");
    map.put("状态", "启用");
    ReflectionUtils.setPatterns(pattern);
    Student stu = BeanUtils.toBean(map, Student.class, new StateConverter());
    assertNotNull(stu);
    assertEquals("张三", stu.getName());
    assertEquals(Integer.valueOf(18), stu.getAge());
    assertEquals(Double.valueOf(99.3), stu.getChineseScore());
    assertEquals(Double.valueOf(89.34), stu.getMathsScore());
    assertEquals(Integer.valueOf(2), stu.getGender());
    assertEquals(Integer.valueOf(1), stu.getState());
    assertEquals(date, DateFormatUtils.format(stu.getBirthday(), pattern));
}
项目:excel-bean    文件:BeanUtilsTest.java   
@Test
public void testBean2Map() throws ParseException {
    profiler.start("testBean2Map");
    Date date = new Date();
    Student stu = new Student();
    stu.setAge(18);
    stu.setBirthday(date);
    stu.setChineseScore(99.9);
    stu.setGender(1);
    stu.setMathsScore(88.3);
    stu.setName("张三");
    stu.setState(2);

    ReflectionUtils.setPatterns(pattern);
    Map<String, String> map = BeanUtils.toMap(stu, new StateConverter());
    assertNotNull(stu);
    assertEquals("18", map.get("年龄"));
    assertEquals("张三", map.get("姓名"));
    assertEquals("88.3", map.get("数学分数"));
    assertEquals("99.9", map.get("语文分数"));
    assertEquals("男", map.get("性别"));
    assertEquals("注销", map.get("状态"));
    assertEquals(DateFormatUtils.format(date, pattern), map.get("生日"));
}
项目:alimama    文件:ShuaOline.java   
public static void execte(WebDriver webDriver) {
    for (int i = 0; i < len; i++) {
        // https://detail.m.tmall.com/item.htm?id=26304648306
        try {
            webGet(webDriver, url);
            // Thread.sleep(sleep);
        } catch (Exception e) {
            e.printStackTrace();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }
        System.out.println("当前已刷>>>>>>>>>>>>>>>>>" + i);
    }
    System.out.println(DateFormatUtils.format(new Date(), "yyyyMMddHHmmss"));
}
项目:mention-notifications-ejb    文件:RtNotifications.java   
@Override
public List<JsonObject> fetch() throws IOException {
    List<JsonObject> filtered = new ArrayList<JsonObject>();
    JsonArray notifications = this.request().fetch()
        .as(RestResponse.class).assertStatus(HttpURLConnection.HTTP_OK)
        .as(JsonResponse.class).json().readArray();
    this.lastReadAt = DateFormatUtils.formatUTC(
        new Date(System.currentTimeMillis()),
        "yyyy-MM-dd'T'HH:mm:ss'Z'"
    );
    log.info("Found " + notifications.size() + " new notifications!");
    if(notifications.size() > 0) {
        List<JsonObject> unfiltered = new ArrayList<JsonObject>();
        for(int i=0; i<notifications.size(); i++) {
            unfiltered.add(notifications.getJsonObject(i));
        }
        filtered = this.reason.filter(unfiltered);
    }
    return filtered;
}
项目:bamboobsc    文件:HistoryItemScoreReportContentQueryUtils.java   
public static List<String> getLineChartCategories(String dateVal, int dataSize) throws Exception {
    List<String> categories = new LinkedList<String>();
    if (dataSize < 0) {
        throw new ServiceException("data-size error!");
    }       
    Date endDate = DateUtils.parseDate(dateVal, new String[]{"yyyyMMdd"});
    int dateRange = dataSize -1;
    if (dateRange < 0) {
        dateRange = 0;
    }
    if (dateRange == 0) {
        categories.add( DateFormatUtils.format(endDate, "yyyy/MM/dd") );
        return categories;
    }
    Date startDate = DateUtils.addDays(endDate, (dateRange * -1) );
    for (int i=0; i<dataSize; i++) {
        Date currentDate = DateUtils.addDays(startDate, i);
        String currentDateStr = DateFormatUtils.format(currentDate, "yyyy/MM/dd");
        categories.add(currentDateStr);
    }
    return categories;
}
项目:Tank    文件:AgentBean.java   
public void getAgentStatus(String jobId) {
    VMTracker tracker = new VMTrackerImpl();
    CloudVmStatusContainer container = tracker.getVmStatusForJob(jobId);
    Set<CloudVmStatus> statuses = container.getStatuses();

    for (CloudVmStatus cloudVmStatus : statuses) {
        AgentStatusReporter asr = new AgentStatusReporter();
        asr.setActiveUsers(String.valueOf(cloudVmStatus.getCurrentUsers()));
        asr.setInstanceId(cloudVmStatus.getInstanceId());
        asr.setJobId(cloudVmStatus.getJobId());
        asr.setStartTime(DateFormatUtils.format(cloudVmStatus.getStartTime(), "mm/dd/yyyy HH:mm:ss"));
        asr.setEndTime(DateFormatUtils.format(cloudVmStatus.getEndTime(), "mm/dd/yyyy HH:mm:ss"));
        asr.setAgentStatus(cloudVmStatus.getVmStatus().toString());
        asr.setRegion(cloudVmStatus.getVmRegion().toString());
        asr.setRole(cloudVmStatus.getRole().toString());
        asr.setJobStatus(cloudVmStatus.getJobStatus().toString());
        asr.setTotalTime("");
        asr.setTotalUsers(String.valueOf(cloudVmStatus.getTotalUsers()));
        asr.setUsersChange("0");
        agents.add(asr);
    }

}
项目:maker    文件:Lang3Test.java   
@Test
public void dateFormatUtilsDemo() {
    System.out.println(genHeader("DateFormatUtilsDemo"));
    System.out.println("格式化日期输出.");
    System.out.println(DateFormatUtils.format(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss"));

    System.out.println("秒表.");
    StopWatch sw = new StopWatch();
    sw.start();

    for (Iterator<Calendar> iterator = DateUtils.iterator(new Date(), DateUtils.RANGE_WEEK_CENTER); iterator.hasNext();) {
        Calendar cal = (Calendar) iterator.next();
        System.out.println(DateFormatUtils.format(cal.getTime(), "yy-MM-dd HH:mm"));
    }

    sw.stop();
    System.out.println("秒表计时:" + sw.getTime());

}
项目:Couchbase    文件:CouchbaseClusterConnection.java   
public void getReport(final MemTreeBuilder builder) {

        builder.startElement("", "connection", "connection", null);

        builder.startElement("", "id", "id", null);
        builder.characters(getConnectionId().toString());
        builder.endElement();

        builder.startElement("", "username", "username", null);
        builder.characters(getUsername());
        builder.endElement();

        builder.startElement("", "has-bucket-password", "has-bucket-password", null);
        builder.characters((getBucketPassword() == null) ? "false" : "true");
        builder.endElement();

        builder.startElement("", "url", "url", null);
        builder.characters(getConnectionString());
        builder.endElement();

        builder.startElement("", "created", "created", null);
        builder.characters(DateFormatUtils.ISO_8601_EXTENDED_DATETIME_TIME_ZONE_FORMAT.format(creation));
        builder.endElement();

        builder.endElement();
    }
项目:jackdaw    文件:GeneratedCodeGenerator.java   
private void addGeneratedAnnotation(
    final TypeSpec.Builder typeSpecBuilder, final ProcessorContext processorContext
) {
    final AnnotationSpec.Builder annotationBuilder =
        AnnotationSpec.builder(Generated.class)
            .addMember("value", "$S", JackdawProcessor.class.getName());

    if (processorContext.isAddGeneratedDate()) {
        final String currentTime =
            DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.format(new Date());

        annotationBuilder.addMember("date", "$S", currentTime);
    }

    typeSpecBuilder.addAnnotation(annotationBuilder.build());
}
项目:MyBatisPioneer    文件:FileHandler.java   
public static String backup(String origFileName) throws IOException {

        // Get backup file name by inserting timestamp before extension name.
        String timestamp = DateFormatUtils.format(Calendar.getInstance().getTime(), "[yyyy.MM.dd'T'HH.mm.ss]");
        int lastIdxOfDot = origFileName.lastIndexOf(".");
        String backupFileName = origFileName.substring(0, lastIdxOfDot + 1) + timestamp + origFileName.substring(lastIdxOfDot, origFileName.length());

        // Create backup file by renaming original file.
        File origFile = new File(origFileName);
        File backFile = new File(backupFileName);

        logger.info("BACKUP: Begin to make a backup for file: " + origFileName);
        FileUtils.copyFile(origFile, backFile);

        return backupFileName;

    }
项目:garmin-fit-geojson    文件:GarminFitListener.java   
/**
 * This just pulls a handful of values from the session for illustration purposes.
 * @param sessionMesg
 */
@Override
public void onMesg(SessionMesg sessionMesg) {
    if (sessionMesg.getTotalDistance() != null) {
        fitActivity.setTotalMeters(sessionMesg.getTotalDistance().doubleValue());
    }
    if (sessionMesg.getStartTime() != null) {
        final String formatedDate = DateFormatUtils.format( sessionMesg.getStartTime().getDate(), "yyyy-MM-dd'T'HH:mm'Z'", TimeZone.getTimeZone("UTC"));
        fitActivity.setStartTime(formatedDate);
    }
    if (sessionMesg.getTotalTimerTime() != null) {
        fitActivity.setTotalSeconds(sessionMesg.getTotalTimerTime().doubleValue());
    }
    if (sessionMesg.getSport() != null) {
        fitActivity.setSport(sessionMesg.getSport().name());
    }
}
项目:datacollector    文件:BaseTableJdbcSourceIT.java   
protected static String getStringRepOfFieldValueForInsert(Field field) {
  switch (field.getType()) {
    case BYTE_ARRAY:
      //Do a hex encode.
      return Hex.encodeHexString(field.getValueAsByteArray());
    case BYTE:
      return String.valueOf(field.getValueAsInteger());
    case TIME:
      return DateFormatUtils.format(field.getValueAsDate(), "HH:mm:ss.SSS");
    case DATE:
      return DateFormatUtils.format(field.getValueAsDate(), "yyyy-MM-dd");
    case DATETIME:
      return DateFormatUtils.format(field.getValueAsDate(), "yyyy-MM-dd HH:mm:ss.SSS");
    case ZONED_DATETIME:
      return DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.format(
          field.getValueAsZonedDateTime().toInstant().toEpochMilli()
      );
    default:
      return String.valueOf(field.getValue());
  }
}
项目:nano-framework    文件:ClassCastTest.java   
@Test
public void castByObjectTest() {
    Object val = ClassCast.cast(new BigDecimal(1), Integer.class.getName());
    assertEquals(1, val);

    val = ClassCast.cast(new BigDecimal(1), Long.class.getName());
    assertEquals(1L, val);

    val = ClassCast.cast(new BigDecimal(1), Double.class.getName());
    assertEquals(1D, val);

    val = ClassCast.cast(new BigDecimal(1), Float.class.getName());
    assertEquals(1F, val);

    Date now = new Timestamp(System.currentTimeMillis());
    val = ClassCast.cast(DateFormatUtils.format(now, Pattern.TIMESTAMP.get()), Timestamp.class.getName());
    assertEquals(now.getTime(), ((Timestamp) val).getTime());
}
项目:message-server    文件:MMXPubSubItemChannel.java   
private void parsePayload(Element payloadElement) {
  if(payloadElement != null) {
    Document d = payloadElement.getDocument();
    Node mmxPayloadNode = d.selectSingleNode(String.format("/*[name()='%s']/*[name()='%s']", Constants.MMX_ELEMENT, Constants.MMX_PAYLOAD));

    if(mmxPayloadNode != null) {
      String mtype = mmxPayloadNode.valueOf("@mtype");
      String stamp = DateFormatUtils.format(new DateTime(mmxPayloadNode.valueOf("@stamp")).toDate(), "yyyy-MM-dd'T'HH:mm:ss'Z'", TimeZone.getTimeZone("UTC"));
      String data = mmxPayloadNode.getText();
      payload = new MMXPubSubPayload(mtype, stamp, data);
    }

    Node mmxMetaNode = d.selectSingleNode(String.format("/*[name()='%s']/*[name()='%s']", Constants.MMX_ELEMENT, Constants.MMX_META));

    if(mmxMetaNode != null) {
      meta = getMapFromJsonString(mmxMetaNode.getText());
    }
  }
}
项目:message-server    文件:MMXPubSubItem.java   
private void parsePayload(Element payloadElement) {
  if(payloadElement != null) {
    Document d = payloadElement.getDocument();
    Node mmxPayloadNode = d.selectSingleNode(String.format("/*[name()='%s']/*[name()='%s']", Constants.MMX_ELEMENT, Constants.MMX_PAYLOAD));

    if(mmxPayloadNode != null) {
      String mtype = mmxPayloadNode.valueOf("@mtype");
      String stamp = DateFormatUtils.format(new DateTime(mmxPayloadNode.valueOf("@stamp")).toDate(), "yyyy-MM-dd'T'HH:mm:ss'Z'", TimeZone.getTimeZone("UTC"));
      String data = mmxPayloadNode.getText();
      payload = new MMXPubSubPayload(mtype, stamp, data);
    }

    Node mmxMetaNode = d.selectSingleNode(String.format("/*[name()='%s']/*[name()='%s']", Constants.MMX_ELEMENT, Constants.MMX_META));

    if(mmxMetaNode != null) {
      meta = getMapFromJsonString(mmxMetaNode.getText());
    }
  }
}
项目:imcms    文件:DublinCoreTermsMapFactory.java   
public Map<NameSpace, Map<String, String>> getNameSpaceStrings(DublinCoreTerms dublinCoreTerms) {
    Format iso8601Format = DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT;
    return ArrayUtils.toMap(new Object[][]{
            {DublinCoreTerms.DUBLIN_CORE_ELEMENTS_NAME_SPACE, ArrayUtils.toMap(new Object[][]{
                    {"creator", null != dublinCoreTerms.getCreator() ? dublinCoreTerms.getCreator().getName() : null},
                    {"description", dublinCoreTerms.getDescription()},
                    {"identifier", dublinCoreTerms.getIdentifer()},
                    {"title", dublinCoreTerms.getTitle()},
            })},
            {DublinCoreTerms.DUBLIN_CORE_TERMS_NAME_SPACE, ArrayUtils.toMap(new Object[][]{
                    {"created", format(iso8601Format, dublinCoreTerms.getCreated())},
                    {"issued", format(iso8601Format, dublinCoreTerms.getIssued())},
                    {"modified", format(iso8601Format, dublinCoreTerms.getModified())},
            })},
    });
}
项目:syncope    文件:UserITCase.java   
public static UserTO getSampleTO(final String email) {
    UserTO userTO = new UserTO();
    userTO.setRealm(SyncopeConstants.ROOT_REALM);
    userTO.setPassword("password123");
    userTO.setUsername(email);

    userTO.getPlainAttrs().add(attrTO("fullname", email));
    userTO.getPlainAttrs().add(attrTO("firstname", email));
    userTO.getPlainAttrs().add(attrTO("surname", "surname"));
    userTO.getPlainAttrs().add(attrTO("ctype", "a type"));
    userTO.getPlainAttrs().add(attrTO("userId", email));
    userTO.getPlainAttrs().add(attrTO("email", email));
    userTO.getPlainAttrs().add(
            attrTO("loginDate", DateFormatUtils.ISO_8601_EXTENDED_DATETIME_FORMAT.format(new Date())));

    return userTO;
}
项目:graphene-walker    文件:BasicEntityRefFunnel.java   
@Override
public BasicEntityRef to(WalkerEntityref100 f) {
    BasicEntityRef b = new BasicEntityRef();
    b.setAccountNumber(f.getAccountnumber());
    b.setAccountType(f.getAccounttype());
    b.setCustomerNumber(f.getCustomernumber());
    b.setCustomerType(f.getCustomertype());

    b.setDateStart(f.getDatestart() != null ? DateFormatUtils.ISO_DATE_FORMAT
            .format(f.getDatestart()) : null);
    b.setDateEnd(f.getDateend() != null ? DateFormatUtils.ISO_DATE_FORMAT
            .format(f.getDateend()) : null);

    b.setEntityrefId(f.getEntityrefId());

    b.setIdentifier(f.getIdentifier());

    b.setIdentifierColumnSource(f.getIdentifiercolumnsource());
    b.setIdentifierTableSource(f.getIdentifiertablesource());
    b.setIdtypeId(f.getIdtypeId());

    return b;
}
项目:mycollab    文件:ActivityStreamPanel.java   
private void feedBlocksPut(Date currentDate, Date nextDate, CssLayout currentBlock) {
    MHorizontalLayout blockWrapper = new MHorizontalLayout().withSpacing(false).withFullWidth().withStyleName("feed-block-wrap");

    blockWrapper.setDefaultComponentAlignment(Alignment.TOP_LEFT);
    Calendar cal1 = Calendar.getInstance();
    cal1.setTime(currentDate);

    Calendar cal2 = Calendar.getInstance();
    cal2.setTime(nextDate);

    if (cal1.get(Calendar.YEAR) != cal2.get(Calendar.YEAR)) {
        int currentYear = cal2.get(Calendar.YEAR);
        Label yearLbl = ELabel.html("<div>" + String.valueOf(currentYear) + "</div>").withStyleName
                ("year-lbl").withWidthUndefined();
        listContainer.addComponent(yearLbl);
    } else {
        blockWrapper.setMargin(new MarginInfo(true, false, false, false));
    }
    Label dateLbl = new Label(DateFormatUtils.format(nextDate, "dd/MM"));
    dateLbl.setSizeUndefined();
    dateLbl.setStyleName("date-lbl");
    blockWrapper.with(dateLbl, currentBlock).expand(currentBlock);

    listContainer.addComponent(blockWrapper);
}
项目:cantilever    文件:MomentFetcher.java   
public MomentFetcher(Calendar startTime, MessageQueueInterface mqi) {
    this.cal = startTime;
    String timestamp = DateFormatUtils.format(this.cal,
            ConfigurationSingleton.instance
                    .getConfigItem("replay.dateformat"));

    ArrayList<HTTPLogObject> thing = ReplayCache.instance
            .gimmieCache(timestamp);

    logger.info(thing.size() + " events for " + timestamp);

    for (HTTPLogObject s : thing) {
        mqi.deliver(s.getPayload());
        logger.debug(s.getPayload());
    }
    this.cal.add(Calendar.SECOND, 1);
}
项目:iot-java    文件:DeviceLocation.java   
/**
 * Return the <code>JsonObject</code> representation of the <code>DeviceLocation</code> object.
 * @return JsonObject object
 */
public JsonObject toJsonObject() {
    JsonObject json = new JsonObject();
    json.addProperty(this.latitude.getResourceName(), latitude.getValue());
    json.addProperty(this.longitude.getResourceName(), longitude.getValue());
    if(elevation != null) {
        json.addProperty(this.elevation.getResourceName(), elevation.getValue());
    }

    String utcTime = DateFormatUtils.formatUTC(measuredDateTime.getValue(), 
            DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.getPattern());

    json.addProperty(this.measuredDateTime.getResourceName(), utcTime);

    if(accuracy != null) {
        json.addProperty(this.accuracy.getResourceName(), accuracy.getValue());
    }
    return json;
}
项目:QuickProject    文件:FilesGenerator.java   
public void generate() throws GlobalConfigException {
    Configuration cfg = new Configuration();
    File tmplDir = globalConfig.getTmplFile();
    try {
        cfg.setDirectoryForTemplateLoading(tmplDir);
    } catch (IOException e) {
        throw new GlobalConfigException("tmplPath", e);
    }
    cfg.setObjectWrapper(new DefaultObjectWrapper());
    for (Module module : modules) {
        logger.debug("module:" + module.getName());
        for (Bean bean : module.getBeans()) {
            logger.debug("bean:" + bean.getName());
            Map dataMap = new HashMap();
            dataMap.put("bean", bean);
            dataMap.put("module", module);
            dataMap.put("generate", generate);
            dataMap.put("config", config);
            dataMap.put("now", DateFormatUtils.ISO_DATE_FORMAT.format(new Date()));

            generate(cfg, dataMap);
        }
    }
}