Example usage for org.joda.time.format DateTimeFormat forPattern

List of usage examples for org.joda.time.format DateTimeFormat forPattern

Introduction

In this page you can find the example usage for org.joda.time.format DateTimeFormat forPattern.

Prototype

public static DateTimeFormatter forPattern(String pattern) 

Source Link

Document

Factory to create a formatter from a pattern string.

Usage

From source file:cn.teamlab.wg.framework.struts2.tags.ExtDate.java

License:Apache License

public boolean end(Writer writer, String body) {
    String msg = null;/*w  ww.  jav  a  2  s . c o  m*/
    java.util.Date date = null;
    org.joda.time.DateTime dateTime = null;
    org.joda.time.LocalTime time = null;
    // find the name on the valueStack

    try {
        // suport Calendar also
        Object dateObject = findValue(name);
        if (dateObject instanceof org.joda.time.DateTime) {
            try {
                dateTime = (org.joda.time.DateTime) dateObject;
            } catch (Exception e) {
                LOG.error("Could not convert object with key '" + name
                        + "' to a org.joda.time.DateTime instance");
                // bad date, return a blank instead ?
                msg = "";
            }
        } else if (dateObject instanceof org.joda.time.LocalTime) {
            try {
                time = (org.joda.time.LocalTime) dateObject;
            } catch (Exception e) {
                LOG.error("Could not convert object with key '" + name
                        + "' to a org.joda.time.LocalTime instance");
                // bad date, return a blank instead ?
                msg = "";
            }
        } else {
            return super.end(writer, body);
        }
    } catch (Exception e) {
        LOG.error("Could not write out Date tag", e);
    }

    // try to find the format on the stack
    if (format != null) {
        format = findString(format);
    } else if (type != null) {
        format = ConfigurationUtil.getProperty(TYPE_PREFIX + type);
    }

    if (time != null) {
        if (format == null) {
            msg = time.toString(DateTimeFormat.forPattern(JODA_TIME_FORMAT_PATTERN));
        } else {
            msg = time.toString(DateTimeFormat.forPattern(format));
        }
    }

    if (dateTime != null) {
        TextProvider tp = findProviderInStack();
        if (tp != null) {
            if (nice) {
                date = dateTime.toDate();
                msg = formatTime(tp, date);
            } else {
                if (format == null) {
                    String globalFormat = null;

                    // if the format is not specified, fall back using the
                    // defined property DATETAG_PROPERTY
                    globalFormat = tp.getText(DATETAG_PROPERTY);

                    // if tp.getText can not find the property then the
                    // returned string is the same as input =
                    // DATETAG_PROPERTY
                    if (globalFormat != null && !DATETAG_PROPERTY.equals(globalFormat)) {
                        msg = dateTime.toString(DateTimeFormat.forPattern(globalFormat));
                    } else {
                        msg = dateTime.toString(DateTimeFormat.forPattern(JODA_DATE_FORMAT_PATTERN));
                    }
                } else {
                    msg = dateTime.toString(DateTimeFormat.forPattern(format));
                }
            }
        }
    }

    if (msg != null) {
        try {
            if (getVar() == null) {
                writer.write(msg);
            } else {
                putInContext(msg);
            }
        } catch (IOException e) {
            LOG.error("Could not write out Date tag", e);
        }
    }

    return super.end(writer, "");
}

From source file:co.bluepass.web.rest.ClubResource.java

/**
 * Gets customers by club id.//from  ww  w  .  j a  v a  2 s  .  com
 *
 * @param id        the id
 * @param yearMonth the year month
 * @param response  the response
 * @return the customers by club id
 * @throws URISyntaxException the uri syntax exception
 */
@RequestMapping(value = "/clubs/{id}/customers", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<List<User>> getCustomersByClubId(@PathVariable Long id, @RequestParam String yearMonth,
        HttpServletResponse response) throws URISyntaxException {
    log.debug("REST request to get Actions by club id : {}", id);

    List<User> users = new ArrayList<User>();
    List<ReservationHistory> reservationHistories = null;

    if (StringUtils.isNotEmpty(yearMonth)) {
        DateTimeFormatter formatter = DateTimeFormat.forPattern("yyMM");
        DateTime monthStartDate = formatter.parseDateTime(yearMonth);
        DateTime monthEndDate = monthStartDate.dayOfMonth().withMaximumValue();
        monthEndDate = monthEndDate.withTime(23, 59, 59, 59);
        reservationHistories = reservationHistoryRepository.findByClubIdAndUsedAndStartTimeBetween(id, true,
                monthStartDate, monthEndDate);
    } else {
        reservationHistories = reservationHistoryRepository.findByClubIdAndUsed(id, true);
    }

    if (reservationHistories == null || reservationHistories.isEmpty()) {
        return new ResponseEntity<List<User>>(users, HttpStatus.OK);
    }

    Set<Long> userIds = new HashSet<>();
    for (ReservationHistory history : reservationHistories) {
        userIds.add(history.getUserId());
    }

    users = userRepository.findAll(userIds);

    return new ResponseEntity<List<User>>(users, HttpStatus.OK);
}

From source file:com.ace.commons.utils.TimeUtils.java

public static DateTime parse(String time) {
    DateTimeFormatter sFormat = DateTimeFormat.forPattern(DATETIME_DATE_NORMAL_FORMAT);
    DateTimeFormatter lFormat = DateTimeFormat.forPattern(DATETIME_NORMAL_FORMAT);
    //?//from   w w w . j  a va 2  s .c  o  m
    if (time != null && !time.isEmpty()) {
        return time.length() > 10 ? DateTime.parse(time, lFormat) : DateTime.parse(time, sFormat);
    }
    return null;
}

From source file:com.ace.erp.utils.TimeUtils.java

public static DateTime parse(String time) {
    DateTimeFormatter sFormat = DateTimeFormat.forPattern(DATETIME_DATE_NORMAL_FORMAT);
    DateTimeFormatter lFormat = DateTimeFormat.forPattern(DATETIME_NORMAL_FORMAT);
    //?// www.  jav a 2 s.co m
    if (!StringUtils.isNullOrEmpty(time)) {
        return time.length() > 10 ? DateTime.parse(time, lFormat) : DateTime.parse(time, sFormat);
    }
    return null;
}

From source file:com.act.lcms.db.model.ScanFile.java

License:Open Source License

/**
 * This function parses the date from a given scan file's name.
 * @return a local date time//  w  w  w . ja v a  2s.c om
 */
public LocalDateTime getDateFromScanFileTitle() throws Exception {
    for (Pair<Pattern, Map<SCAN_NAME_COMPONENT, Integer>> scan : NAME_EXTRACTION_PATTERNS) {
        Pattern p = scan.getLeft();
        Map<SCAN_NAME_COMPONENT, Integer> groupMap = scan.getRight();
        Matcher m = p.matcher(this.fileName);
        if (m.matches() && groupMap.containsKey(SCAN_NAME_COMPONENT.DATE)) {
            DateTimeFormatter formatter = DateTimeFormat.forPattern(DATE_FORMAT);
            LocalDateTime dateTime = LocalDateTime.parse(m.group(groupMap.get(SCAN_NAME_COMPONENT.DATE)),
                    formatter);
            if (dateTime.getYear() < TWENTYN_INCEPTION) {
                throw new RuntimeException("The date parsed from the file name is malformed.");
            }
            return dateTime;
        }
    }

    // We assume a date will appear in every file name format.
    throw new RuntimeException(String.format("Unable to extract date from scan file name: %s", this.fileName));
}

From source file:com.addthis.hydra.data.filter.bundle.BundleFilterTimeRange.java

License:Apache License

@Override
public void initialize() {
    fields = new String[] { time };
    if (timeFormat != null) {
        format = DateTimeFormat.forPattern(timeFormat);
    }//from w w w.  j  a v  a2 s .  co  m
    if (before != null) {
        tbefore = convertDate(before);
    }
    if (after != null) {
        tafter = convertDate(after);
    }
}

From source file:com.addthis.hydra.data.filter.value.ValueFilterDateRangeLength.java

License:Apache License

protected Interval parseRange(String rangeString) {
    int sepIndex = rangeString.indexOf(dateSep);
    if (sepIndex <= 0 || sepIndex + 1 == rangeString.length()) {
        throw new IllegalArgumentException("Failed to parse date range: " + rangeString);
    }/*  ww  w  . jav a 2  s  . c o m*/

    DateTimeFormatter dtf = DateTimeFormat.forPattern(dateFormat);
    DateTime beg = dtf.parseDateTime(rangeString.substring(0, sepIndex));
    DateTime end = dtf.parseDateTime(rangeString.substring(sepIndex + 1, rangeString.length()));

    return new Interval(beg, end);
}

From source file:com.addthis.hydra.data.filter.value.ValueFilterDateRangeLength.java

License:Apache License

protected int countDays(String dates) {
    DateTimeFormatter dtf = DateTimeFormat.forPattern(dateFormat);
    String[] datesSplit = toArray(dates);
    SortedSet<DateTime> dateSet = new TreeSet<DateTime>();
    for (String strVal : datesSplit) {
        if (strVal.indexOf(dateSep) < 0) {
            dateSet.add(dtf.parseDateTime(strVal));
        } else {//  www  . j  av a  2 s.co m
            Interval interval = parseRange(strVal);
            for (DateTime dt : Dates.iterableInterval(interval, DTimeUnit.DAY)) {
                dateSet.add(dt);
            }
        }
    }
    return dateSet.size();
}

From source file:com.addthis.hydra.data.filter.value.ValueFilterTimeRange.java

License:Apache License

private final void init() {
    if (date == null) {
        date = DateTimeFormat.forPattern(format);
        if (rangeHours > 0 && rangeDays > 0) {
            throw new RuntimeException("rangeHours and rangeDays cannot both be > 0");
        }//from   w  ww. j a va 2  s .c om
    }
}

From source file:com.addthis.hydra.data.query.op.OpDateFormat.java

License:Apache License

public OpDateFormat(String args, ChannelProgressivePromise queryPromise) {
    super(queryPromise);
    try {//  w  w  w. j  av  a  2s  . c o m
        String[] opt = args.split(":");
        if (opt.length >= 2) {
            String[] cval = Strings.splitArray(opt[0], ",");
            incols = new int[cval.length];
            for (int i = 0; i < cval.length; i++) {
                incols[i] = Integer.parseInt(cval[i]);
            }
            outcol = opt.length > 2 ? Integer.parseInt(opt[3]) : incols[0];
            if ((fromMillis = parseMillis(opt[1])) == 0) {
                inFormat = DateTimeFormat.forPattern(opt[1]);
            }
            if ((toMillis = parseMillis(opt[2])) == 0) {
                outFormat = DateTimeFormat.forPattern(opt[2]);
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}