Example usage for java.text DateFormat DateFormat

List of usage examples for java.text DateFormat DateFormat

Introduction

In this page you can find the example usage for java.text DateFormat DateFormat.

Prototype

protected DateFormat() 

Source Link

Document

Create a new date format.

Usage

From source file:net.sf.jabref.model.entry.BibtexEntry.java

/**
 * Returns the contents of the given field, its alias or null if both are
 * not set./*  w  ww . j  ava 2  s  .co  m*/
 * <p>
 * The following aliases are considered (old bibtex <-> new biblatex) based
 * on the BibLatex documentation, chapter 2.2.5:
 * address       <-> location
 * annote         <-> annotation
 * archiveprefix    <-> eprinttype
 * journal       <-> journaltitle
 * key            <-> sortkey
 * pdf          <-> file
 * primaryclass    <-> eprintclass
 * school          <-> institution
 * These work bidirectional.
 * <p>
 * Special attention is paid to dates: (see the BibLatex documentation,
 * chapter 2.3.8)
 * The fields 'year' and 'month' are used if the 'date'
 * field is empty. Conversely, getFieldOrAlias("year") also tries to
 * extract the year from the 'date' field (analogously for 'month').
 */
public String getFieldOrAlias(String name) {
    String fieldValue = getField(name);

    if (!Strings.isNullOrEmpty(fieldValue)) {
        return fieldValue;
    }

    // No value of this field found, so look at the alias
    String aliasForField = EntryConverter.FIELD_ALIASES.get(name);

    if (aliasForField != null) {
        return getField(aliasForField);
    }

    // Finally, handle dates
    if (name.equals("date")) {
        String year = getField("year");
        MonthUtil.Month month = MonthUtil.getMonth(getField("month"));
        if (year != null) {
            if (month.isValid()) {
                return year + '-' + month.twoDigitNumber;
            } else {
                return year;
            }
        }
    }
    if (name.equals("year") || name.equals("month")) {
        String date = getField("date");
        if (date == null) {
            return null;
        }

        // Create date format matching dates with year and month
        DateFormat df = new DateFormat() {

            static final String FORMAT1 = "yyyy-MM-dd";
            static final String FORMAT2 = "yyyy-MM";
            final SimpleDateFormat sdf1 = new SimpleDateFormat(FORMAT1);
            final SimpleDateFormat sdf2 = new SimpleDateFormat(FORMAT2);

            @Override
            public StringBuffer format(Date dDate, StringBuffer toAppendTo, FieldPosition fieldPosition) {
                throw new UnsupportedOperationException();
            }

            @Override
            public Date parse(String source, ParsePosition pos) {
                if ((source.length() - pos.getIndex()) == FORMAT1.length()) {
                    return sdf1.parse(source, pos);
                }
                return sdf2.parse(source, pos);
            }
        };

        try {
            Date parsedDate = df.parse(date);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(parsedDate);
            if (name.equals("year")) {
                return Integer.toString(calendar.get(Calendar.YEAR));
            }
            if (name.equals("month")) {
                return Integer.toString(calendar.get(Calendar.MONTH) + 1); // Shift by 1 since in this calendar Jan = 0
            }
        } catch (ParseException e) {
            // So not a date with year and month, try just to parse years
            df = new SimpleDateFormat("yyyy");

            try {
                Date parsedDate = df.parse(date);
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(parsedDate);
                if (name.equals("year")) {
                    return Integer.toString(calendar.get(Calendar.YEAR));
                }
            } catch (ParseException e2) {
                LOGGER.warn("Could not parse entry " + name, e2);
                return null; // Date field not in valid format
            }
        }
    }
    return null;
}

From source file:com.opendoorlogistics.components.gantt.GanttChartComponent.java

@Override
public void execute(final ComponentExecutionApi api, int mode, Object configuration,
        ODLDatastore<? extends ODLTable> ioDs, ODLDatastoreAlterable<? extends ODLTableAlterable> outputDs) {
    // Get items and sort by resource then date
    final StringConventions sc = api.getApi().stringConventions();
    List<GanttItem> items = GanttItem.beanMapping.getTableMapping(0).readObjectsFromTable(ioDs.getTableAt(0));

    // Rounding doubles to longs can create small errors where a start time is 1 millisecond after an end.
    // Set all start times to be <= end time
    for (GanttItem item : items) {
        if (item.getStart() == null || item.getEnd() == null) {
            throw new RuntimeException("Found Gannt item with null start or end time.");
        }//from  w  ww .  j  a va  2  s .  com

        if (item.getStart().getValue() > item.getEnd().getValue()) {
            item.setStart(item.getEnd());
        }
    }

    Collections.sort(items, new Comparator<GanttItem>() {

        @Override
        public int compare(GanttItem o1, GanttItem o2) {
            int diff = sc.compareStandardised(o1.getResourceId(), o2.getResourceId());
            if (diff == 0) {
                diff = o1.getStart().compareTo(o2.getStart());
            }
            if (diff == 0) {
                diff = o1.getEnd().compareTo(o2.getEnd());
            }
            if (diff == 0) {
                diff = sc.compareStandardised(o1.getActivityId(), o2.getActivityId());
            }
            if (diff == 0) {
                diff = Colours.compare(o1.getColor(), o2.getColor());
            }
            return diff;
        }
    });

    // Filter any zero duration items
    Iterator<GanttItem> it = items.iterator();
    while (it.hasNext()) {
        GanttItem item = it.next();
        if (item.getStart().compareTo(item.getEnd()) == 0) {
            it.remove();
        }
    }

    // Get average colour for each activity type
    Map<String, CalculateAverageColour> calcColourMap = api.getApi().stringConventions()
            .createStandardisedMap();
    for (GanttItem item : items) {
        CalculateAverageColour calc = calcColourMap.get(item.getActivityId());
        if (calc == null) {
            calc = new CalculateAverageColour();
            calcColourMap.put(item.getActivityId(), calc);
        }
        calc.add(item.getColor());
    }

    // Put into colour map
    Map<String, Color> colourMap = api.getApi().stringConventions().createStandardisedMap();
    for (Map.Entry<String, CalculateAverageColour> entry : calcColourMap.entrySet()) {
        colourMap.put(entry.getKey(), entry.getValue().getAverage());
    }

    // Split items by resource
    ArrayList<ArrayList<GanttItem>> splitByResource = new ArrayList<>();
    ArrayList<GanttItem> current = null;
    for (GanttItem item : items) {
        if (current == null
                || sc.compareStandardised(current.get(0).getResourceId(), item.getResourceId()) != 0) {
            current = new ArrayList<>();
            splitByResource.add(current);
        }
        current.add(item);
    }

    // put into jfreechart's task data structure
    TaskSeries ts = new TaskSeries("Resources");
    for (ArrayList<GanttItem> resource : splitByResource) {
        // get earliest and latest time (last time may not be in the last item)
        ODLTime earliest = resource.get(0).getStart();
        ODLTime latest = null;
        for (GanttItem item : resource) {
            if (latest == null || latest.compareTo(item.getEnd()) < 0) {
                latest = item.getEnd();
            }
        }

        Task task = new Task(resource.get(0).getResourceId(), new Date(earliest.getTotalMilliseconds()),
                new Date(latest.getTotalMilliseconds()));

        // add all items as subtasks
        for (GanttItem item : resource) {
            task.addSubtask(new MySubtask(item, new Date(item.getStart().getTotalMilliseconds()),
                    new Date(item.getEnd().getTotalMilliseconds())));
        }

        ts.add(task);
    }
    TaskSeriesCollection collection = new TaskSeriesCollection();
    collection.add(ts);

    // Create the plot
    CategoryAxis categoryAxis = new CategoryAxis(null);
    DateAxis dateAxis = new DateAxis("Time");
    CategoryItemRenderer renderer = new MyRenderer(collection, colourMap);
    final CategoryPlot plot = new CategoryPlot(collection, categoryAxis, dateAxis, renderer);
    plot.setOrientation(PlotOrientation.HORIZONTAL);
    plot.getDomainAxis().setLabel(null);

    ((DateAxis) plot.getRangeAxis()).setDateFormatOverride(new DateFormat() {

        @Override
        public Date parse(String source, ParsePosition pos) {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) {
            toAppendTo.append(new ODLTime(date.getTime()).toString());
            return toAppendTo;
        }
    });

    // Create the chart and apply the standard theme without shadows to it
    api.submitControlLauncher(new ControlLauncherCallback() {

        @Override
        public void launchControls(ComponentControlLauncherApi launcherApi) {
            JFreeChart chart = new JFreeChart(null, JFreeChart.DEFAULT_TITLE_FONT, plot, true);
            StandardChartTheme theme = new StandardChartTheme("standard theme", false);
            theme.setBarPainter(new StandardBarPainter());
            theme.apply(chart);

            class MyPanel extends ChartPanel implements Disposable {

                public MyPanel(JFreeChart chart) {
                    super(chart);
                }

                @Override
                public void dispose() {
                    // TODO Auto-generated method stub

                }

            }
            MyPanel chartPanel = new MyPanel(chart);
            launcherApi.registerPanel("Resource Gantt", null, chartPanel, true);
        }
    });

}

From source file:net.sf.jabref.model.entry.BibEntry.java

/**
 * Returns the contents of the given field, its alias or null if both are
 * not set./*w  w  w  . ja  v  a2s .  co  m*/
 * <p>
 * The following aliases are considered (old bibtex <-> new biblatex) based
 * on the BibLatex documentation, chapter 2.2.5:
 * address      <-> location
 * annote           <-> annotation
 * archiveprefix    <-> eprinttype
 * journal      <-> journaltitle
 * key              <-> sortkey
 * pdf          <-> file
 * primaryclass     <-> eprintclass
 * school           <-> institution
 * These work bidirectional.
 * <p>
 * Special attention is paid to dates: (see the BibLatex documentation,
 * chapter 2.3.8)
 * The fields 'year' and 'month' are used if the 'date'
 * field is empty. Conversely, getFieldOrAlias("year") also tries to
 * extract the year from the 'date' field (analogously for 'month').
 */
public Optional<String> getFieldOrAlias(String name) {
    Optional<String> fieldValue = getFieldOptional(toLowerCase(name));

    if (fieldValue.isPresent() && !fieldValue.get().isEmpty()) {
        return fieldValue;
    }

    // No value of this field found, so look at the alias
    String aliasForField = EntryConverter.FIELD_ALIASES.get(name);

    if (aliasForField != null) {
        return getFieldOptional(aliasForField);
    }

    // Finally, handle dates
    if (FieldName.DATE.equals(name)) {
        Optional<String> year = getFieldOptional(FieldName.YEAR);
        if (year.isPresent()) {
            MonthUtil.Month month = MonthUtil.getMonth(getFieldOptional(FieldName.MONTH).orElse(""));
            if (month.isValid()) {
                return Optional.of(year.get() + '-' + month.twoDigitNumber);
            } else {
                return year;
            }
        }
    }
    if (FieldName.YEAR.equals(name) || FieldName.MONTH.equals(name)) {
        Optional<String> date = getFieldOptional(FieldName.DATE);
        if (!date.isPresent()) {
            return Optional.empty();
        }

        // Create date format matching dates with year and month
        DateFormat df = new DateFormat() {

            static final String FORMAT1 = "yyyy-MM-dd";
            static final String FORMAT2 = "yyyy-MM";
            final SimpleDateFormat sdf1 = new SimpleDateFormat(FORMAT1);
            final SimpleDateFormat sdf2 = new SimpleDateFormat(FORMAT2);

            @Override
            public StringBuffer format(Date dDate, StringBuffer toAppendTo, FieldPosition fieldPosition) {
                throw new UnsupportedOperationException();
            }

            @Override
            public Date parse(String source, ParsePosition pos) {
                if ((source.length() - pos.getIndex()) == FORMAT1.length()) {
                    return sdf1.parse(source, pos);
                }
                return sdf2.parse(source, pos);
            }
        };

        try {
            Date parsedDate = df.parse(date.get());
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(parsedDate);
            if (FieldName.YEAR.equals(name)) {
                return Optional.of(Integer.toString(calendar.get(Calendar.YEAR)));
            }
            if (FieldName.MONTH.equals(name)) {
                return Optional.of(Integer.toString(calendar.get(Calendar.MONTH) + 1)); // Shift by 1 since in this calendar Jan = 0
            }
        } catch (ParseException e) {
            // So not a date with year and month, try just to parse years
            df = new SimpleDateFormat("yyyy");

            try {
                Date parsedDate = df.parse(date.get());
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(parsedDate);
                if (FieldName.YEAR.equals(name)) {
                    return Optional.of(Integer.toString(calendar.get(Calendar.YEAR)));
                }
            } catch (ParseException e2) {
                LOGGER.warn("Could not parse entry " + name, e2);
                return Optional.empty(); // Date field not in valid format
            }
        }
    }
    return Optional.empty();
}

From source file:com.sun.socialsite.util.DateUtil.java

public static DateFormat roundedRelativeFormat() {
    return new DateFormat() {

        public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) {
            // TODO: Some better (and more localizable) way to do this?
            Date now = new Date();
            long secondsDiff = (now.getTime() - date.getTime()) / 1000;
            if (secondsDiff <= 1) {
                return toAppendTo.append("1 second ago");
            } else if (secondsDiff < 60) {
                return toAppendTo.append(secondsDiff).append(" seconds ago");
            } else if (secondsDiff < (2 * 60)) {
                return toAppendTo.append("1 minute ago");
            } else if (secondsDiff < (60 * 60)) {
                return toAppendTo.append((secondsDiff / 60)).append(" minutes ago");
            } else if (secondsDiff < (2 * 60 * 60)) {
                return toAppendTo.append("1 hour ago");
            } else if (secondsDiff < (24 * 60 * 60)) {
                return toAppendTo.append((secondsDiff / (60 * 60))).append(" hours ago");
            } else if (secondsDiff < (2 * 24 * 60 * 60)) {
                return toAppendTo.append("yesterday");
            } else {
                return toAppendTo.append((secondsDiff / (24 * 60 * 60))).append(" days ago");
            }/*from w ww .ja va2s .co m*/
        }

        public Date parse(String source, ParsePosition pos) {
            throw new UnsupportedOperationException();
        }
    };
}