Example usage for org.joda.time.format DateTimeFormatter print

List of usage examples for org.joda.time.format DateTimeFormatter print

Introduction

In this page you can find the example usage for org.joda.time.format DateTimeFormatter print.

Prototype

public String print(ReadablePartial partial) 

Source Link

Document

Prints a ReadablePartial to a new String.

Usage

From source file:de.dekstop.cosm.Coverage.java

License:Open Source License

/**
 * @param args/*w  w  w .  j  a  v a  2  s .co  m*/
 */
public static void main(String[] args) throws Exception {
    if (args.length < 3 || args.length > 4) {
        System.out.println("<second|minute|hour|day> <data-filename> <output-dir> [format]");
        System.out.println("File format is tab-separated text: <tag> <timestamp>");
        System.out.println("Reads ISO timestamps by default: yyyy-MM-dd HH:mm:ss");
        System.out.println("Output order reflects the order of tags in input data.");
        System.exit(1);
    }

    // Args
    CoverageType type = getType(args[0]);
    if (type == null) {
        System.out.println("Can't determine coverage type: " + args[0] + " Reverting to default type.");
        type = CoverageType.DAY;
    }
    String dataFilename = args[1];
    String outputDirname = args[2];
    String dateFormat = defaultDateFormat;
    if (args.length == 4) {
        dateFormat = args[3];
    }

    File dataFile = new File(dataFilename);

    String name = dataFile.getName();
    if (name.lastIndexOf('.') != -1) {
        name = name.substring(0, name.lastIndexOf('.'));
    }
    File imageFile = new File(outputDirname,
            String.format("%s-%s.%s", name, type.toString().toLowerCase(), imageFormat));
    System.out.println(imageFile.getName() + " ...");

    File outputDir = new File(outputDirname);
    if (!outputDir.exists()) {
        outputDir.mkdirs();
    }

    // Load data
    // 2011-11-06T06:14:32.656171Z
    List<TaggedDateTime> records = new FileImporter<TaggedDateTime>(new TaggedDateParser(dateFormat))
            .parse(dataFile);
    HashMap<String, List<DateTime>> entries = new HashMap<String, List<DateTime>>();
    List<String> entryOrder = new ArrayList<String>();
    DateTime minDate = records.get(0).date;
    DateTime maxDate = records.get(0).date;
    for (TaggedDateTime record : records) {
        if (!entries.containsKey(record.tag)) {
            entryOrder.add(record.tag);
            entries.put(record.tag, new ArrayList<DateTime>());
        }
        entries.get(record.tag).add(record.date);
        minDate = record.date.compareTo(minDate) < 0 ? record.date : minDate;
        maxDate = record.date.compareTo(maxDate) >= 0 ? record.date : maxDate;
    }
    System.out.println(String.format("Loaded %d records for %d tags.", records.size(), entries.size()));
    DateTimeFormatter df = DateTimeFormat.forPattern(defaultDateFormat).withZone(DateTimeZone.UTC);
    System.out.println(String.format("First date: %s", df.print(minDate)));
    System.out.println(String.format("Last date: %s", df.print(maxDate)));

    // Image
    int width = getDistance(type, minDate, maxDate) + 1;
    int height = entries.size();

    System.out.println(String.format("Image dimensions: %d x %d", width, height));

    BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

    int y = 0;
    for (String tag : entryOrder) {
        for (DateTime date : entries.get(tag)) {
            int x = getDistance(type, minDate, date);
            img.setRGB(x, y, 0x0ffffffff);
        }
        y++;
    }
    // Graphics2D g2 = img.createGraphics();
    // g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    // Write to file
    ImageIO.write(img, imageFormat, imageFile);
}

From source file:de.geeksfactory.opacclient.frontend.AccountFragment.java

License:MIT License

private void export() {
    if (refreshing) {
        Toast.makeText(getActivity(), R.string.account_no_concurrent, Toast.LENGTH_LONG).show();
        if (!refreshing) {
            refresh();//www .j  a v  a 2s  . c  o m
        }
        return;
    }

    Context ctx = getActivity() != null ? getActivity() : OpacClient.getEmergencyContext();
    AccountDataSource adatasource = new AccountDataSource(ctx);
    AccountData data = adatasource.getCachedAccountData(account);
    LocalDateTime dt = new LocalDateTime(adatasource.getCachedAccountDataTime(account));

    if (data == null)
        return;

    StringBuilder string = new StringBuilder();

    DateTimeFormatter fmt1 = DateTimeFormat.shortDateTime()
            .withLocale(getResources().getConfiguration().locale);
    DateTimeFormatter fmt2 = DateTimeFormat.shortDate().withLocale(getResources().getConfiguration().locale);
    String dateStr = fmt1.print(dt);
    string.append(getResources().getString(R.string.accountdata_export_header, account.getLabel(), dateStr));
    string.append("\n\n");
    string.append(getResources().getString(R.string.lent_head));
    string.append("\n\n");
    for (LentItem item : data.getLent()) {
        appendIfNotEmpty(string, item.getTitle(), R.string.accountdata_title);
        appendIfNotEmpty(string, item.getAuthor(), R.string.accountdata_author);
        appendIfNotEmpty(string, item.getFormat(), R.string.accountdata_format);
        appendIfNotEmpty(string, item.getStatus(), R.string.accountdata_status);
        appendIfNotEmpty(string, item.getBarcode(), R.string.accountdata_lent_barcode);
        if (item.getDeadline() != null) {
            appendIfNotEmpty(string, fmt2.print(item.getDeadline()), R.string.accountdata_lent_deadline);
        }
        appendIfNotEmpty(string, item.getHomeBranch(), R.string.accountdata_lent_home_branch);
        appendIfNotEmpty(string, item.getLendingBranch(), R.string.accountdata_lent_lending_branch);
        string.append("\n");
    }

    if (data.getLent().size() == 0) {
        string.append(getResources().getString(R.string.lent_none));
    }

    string.append(getResources().getString(R.string.reservations_head));
    string.append("\n\n");
    for (ReservedItem item : data.getReservations()) {
        appendIfNotEmpty(string, item.getTitle(), R.string.accountdata_title);
        appendIfNotEmpty(string, item.getAuthor(), R.string.accountdata_author);
        appendIfNotEmpty(string, item.getFormat(), R.string.accountdata_format);
        appendIfNotEmpty(string, item.getStatus(), R.string.accountdata_status);
        if (item.getReadyDate() != null) {
            appendIfNotEmpty(string, fmt2.print(item.getReadyDate()), R.string.accountdata_reserved_ready_date);
        }
        if (item.getExpirationDate() != null) {
            appendIfNotEmpty(string, fmt2.print(item.getExpirationDate()),
                    R.string.accountdata_reserved_expiration_date);
        }
        appendIfNotEmpty(string, item.getBranch(), R.string.accountdata_reserved_branch);
        string.append("\n");
    }

    if (data.getReservations().size() == 0) {
        string.append(getResources().getString(R.string.reservations_none));
    }

    Intent sendIntent = new Intent();
    sendIntent.setAction(Intent.ACTION_SEND);
    sendIntent.putExtra(Intent.EXTRA_TEXT, string.toString());
    sendIntent.setType("text/plain");
    startActivity(Intent.createChooser(sendIntent, getResources().getText(R.string.share_dialog_select)));
}

From source file:de.heartbeat.backend.dashboard.ArchivedAlarmPage.java

License:Apache License

public ArchivedAlarmPage(PageParameters parameters) {
    super(parameters);
    WebMarkupContainer archivedTable = new WebMarkupContainer("archivedTable");
    Session session = sessionFactory.openSession();
    session.beginTransaction();/*from   ww  w. j  av  a 2 s. com*/
    heartBeatListArchived
            .addAll(session.createCriteria(HeartBeat.class).add(Restrictions.eq("archived", true)).list());
    session.getTransaction().commit();
    session.close();
    Collections.sort(heartBeatListArchived);

    ListView archivedView = new ListView("heartBeatCalledView", heartBeatListArchived) {
        @Override
        protected void populateItem(ListItem item) {
            final HeartBeat hb = (HeartBeat) item.getModelObject();
            final Person pers = hb.getPerson();
            DateTime date = new DateTime(hb.getTime());
            DateTimeFormatter fmt = DateTimeFormat.forPattern("dd.MM.yyyy HH:mm:ss");
            String str = fmt.print(date);
            item.add(new Label("name", pers.getFirstName() + " " + pers.getLastName()));
            item.add(new Label("time", str));
            item.add(new Label("pulse", hb.getPulse()));
        }
    };

    archivedTable.add(archivedView);
    add(archivedTable);
}

From source file:de.heartbeat.backend.dashboard.HeartBeatOverview.java

License:Apache License

public HeartBeatOverview(PageParameters parameters) {
    super(parameters);
    final WebMarkupContainer table = new WebMarkupContainer("table");
    WebMarkupContainer alertTable = new WebMarkupContainer("alertTable");
    table.setOutputMarkupId(true);//from   www.j av  a2s  .c om
    table.add(new AbstractAjaxTimerBehavior(Duration.seconds(10)) {

        @Override
        protected void onTimer(AjaxRequestTarget art) {
            heartBeatList.clear();
            session = sessionFactory.openSession();
            session.beginTransaction();
            heartBeatList
                    .addAll(session.createCriteria(HeartBeat.class).add(Restrictions.eq("alert", true)).list());
            session.getTransaction().commit();
            session.close();
            Collections.sort(heartBeatList);
            Collections.reverse(heartBeatList);
            art.add(table);
        }
    });

    session = sessionFactory.openSession();
    session.beginTransaction();
    heartBeatList.addAll(session.createCriteria(HeartBeat.class).add(Restrictions.eq("alert", true)).list());

    session.getTransaction().commit();
    session.close();
    Collections.sort(heartBeatList);
    Collections.reverse(heartBeatList);

    ListView alertView = new ListView("heartBeatAlertView", heartBeatList) {
        @Override
        protected void populateItem(ListItem item) {
            final HeartBeat hb = (HeartBeat) item.getModelObject();
            final Person pers = hb.getPerson();
            DateTime date = new DateTime(hb.getTime());
            DateTimeFormatter fmt = DateTimeFormat.forPattern("dd.MM.yyyy HH:mm:ss");
            String str = fmt.print(date);
            item.add(new Label("name", pers.getFirstName() + " " + pers.getLastName()));
            item.add(new Label("time", str));
            item.add(new Label("pulse", hb.getPulse()));
            item.add(new Label("adress", pers.getAdress()));
            item.add(new Link("skypeCall") {
                @Override
                public void onClick() {
                    try {
                        hb.setCalled(true);
                        Session session = sessionFactory.openSession();
                        session.beginTransaction();
                        session.saveOrUpdate(hb);
                        session.getTransaction().commit();
                        session.close();
                        Skype.call(Constants.SKYPE_FRIEND_NICKNAME);
                    } catch (SkypeException ex) {
                        Logger.getLogger(HeartBeatOverview.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            });

            item.add(new Link("skypeMessage") {
                @Override
                public void onClick() {
                    try {
                        String message = "dude, dein Puls";
                        Skype.chat(Constants.SKYPE_FRIEND_NICKNAME).send(message);
                    } catch (SkypeException ex) {
                        Logger.getLogger(HeartBeatOverview.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            });
            Link emergency = new Link("emergency") {
                @Override
                public void onClick() {
                    hb.setAlert(true);
                    hb.setEmergency(true);
                    Session session = sessionFactory.openSession();
                    session.beginTransaction();
                    session.saveOrUpdate(hb);
                    session.getTransaction().commit();
                    session.close();
                }
            };
            Link archive = new Link("archived") {
                @Override
                public void onClick() {
                    hb.setCalled(false);
                    hb.setAlert(false);
                    hb.setArchived(true);
                    Session session = sessionFactory.openSession();
                    session.beginTransaction();
                    session.saveOrUpdate(hb);
                    session.getTransaction().commit();
                    session.close();
                    heartBeatList.remove(hb);
                }
            };

            emergency.setVisible(hb.isCalled());
            item.add(emergency);
            archive.setVisible(hb.isEmergency());
            item.add(archive);
        }
    };

    alertTable.add(alertView);
    table.add(alertTable);
    add(table);
}

From source file:de.raion.xmppbot.command.DilbertCommand.java

License:Apache License

private String createRandomUrl() {

    DateTime minDate = new DateTime(2006, 1, 1, 0, 0, 0);
    DateTime maxDate = new DateTime(System.currentTimeMillis());

    int randomYear = getRandomInRange(minDate.getYear(), maxDate.getYear());
    int randomMonth = getRandomInRange(1, 12);
    int randomDay = getRandomInRange(1, getDaysInMonth(randomYear, randomMonth));

    DateTime randomDate = new DateTime(randomYear, randomMonth, randomDay, 0, 0, 0);
    DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd");

    StringBuilder builder = new StringBuilder(RANDOM_BASE_URL);
    builder.append(formatter.print(randomDate));
    return builder.toString();
}

From source file:di.uniba.it.tee2.util.TEEUtils.java

License:Open Source License

/**
 * @param oldDate/*  w w  w.  ja  v a2  s.  c om*/
 * @return
 * @throws java.text.ParseException
 */
public static String normalizeTime(String oldDate) throws Exception {
    Date now = new Date();
    if (oldDate.equals("PRESENT_REF")) {
        oldDate = new SimpleDateFormat("yyyy-MM-dd").format(now);
    } else if (oldDate.endsWith("FA")) {
        oldDate = oldDate.replace("FA", "09-23");
    } else if (oldDate.endsWith("WI")) {
        oldDate = oldDate.replace("WI", "12-21");
    } else if (oldDate.endsWith("SU")) {
        oldDate = oldDate.replace("SU", "06-20");
    } else if (oldDate.endsWith("SP")) {
        oldDate = oldDate.replace("SP", "03-20");
    } else if (oldDate.equals("PAST_REF") || (oldDate.endsWith("WE"))) {
        return "";
    } else if (oldDate.equals("FUTURE_REF")) {
        return new SimpleDateFormat("yyyyMMdd").format(now);
    }

    DateTime oldD = DateTime.parse(oldDate);

    DateTimeFormatter OldDFmt = ISODateTimeFormat.date();
    String str = OldDFmt.print(oldD);

    Date date = new SimpleDateFormat("yyyy-MM-dd").parse(str);
    String newDate = DateTools.dateToString(date, DateTools.Resolution.DAY);

    return newDate;
}

From source file:divconq.util.TimeUtil.java

License:Open Source License

/**
 * Format date and time in Long format//from  w  w  w.  j  a va2s . c  om
 * 
 * @param at datetime to format
 * @param locale which locale to use 
 * @return formatted datetime
 */
static public String fmtDateTimeLong(DateTime at, String locale) {
    if (at == null)
        return null;

    // TODO user locale to look up format
    DateTimeFormatter fmt = DateTimeFormat.forPattern("MMMM dd yyyy hh:mm:ss a z");
    return fmt.print(at);
}

From source file:divconq.util.TimeUtil.java

License:Open Source License

/**
 * Format date in Long format//from  ww w.  java  2s .com
 * 
 * @param at datetime to format
 * @param locale which locale to use 
 * @return formatted date
 */
static public String fmtDateLong(DateTime at, String locale) {
    if (at == null)
        return null;

    // TODO user locale to look up format
    DateTimeFormatter fmt = DateTimeFormat.forPattern("MMMM dd yyyy");
    return fmt.print(at);
}

From source file:dk.dma.epd.common.prototype.gui.voct.SARPanelCommon.java

License:Apache License

private void setDatumPointData(DatumPointData data) {
    sarData = data;//from   ww w  . j av  a  2  s.  co  m

    lblSarType.setText("Datum Point");

    CardLayout cl = (CardLayout) (datumPanel.getLayout());
    cl.show(datumPanel, DATUMPOINTDATUM);

    DateTimeFormatter fmt = DateTimeFormat.forPattern("HH':'mm '-' dd'/'MM");

    lkpDate.setText(fmt.print(data.getLKPDate()));
    cssDateStart.setText(fmt.print(data.getCSSDate()));
    timeElapsed.setText(Formatter.formatHours(data.getTimeElasped()) + "");

    rdvDirection.setText(Formatter.formatDouble(data.getRdvDirectionDownWind(), 2) + "");
    rdvSpeed.setText(Formatter.formatDouble(data.getRdvSpeedDownWind(), 2) + " kn");

    datumPointDatumPanel.setDatumLatDownWind(data.getDatumDownWind().getLatitudeAsString());
    datumPointDatumPanel.setDatumLonDownWind(data.getDatumDownWind().getLongitudeAsString());
    datumPointDatumPanel
            .setrdvDistanceDownWind(Formatter.formatDouble(data.getRdvDistanceDownWind(), 2) + " nm");
    datumPointDatumPanel.setdatumRadiusDownWind(Formatter.formatDouble(data.getRadiusDownWind(), 2) + " nm");

    datumPointDatumPanel.setDatumLatMin(data.getDatumMin().getLatitudeAsString());
    datumPointDatumPanel.setDatumLonMin(data.getDatumMin().getLongitudeAsString());
    datumPointDatumPanel.setrdvDistanceMin(Formatter.formatDouble(data.getRdvDistanceMin(), 2) + " nm");
    datumPointDatumPanel.setdatumRadiusMin(Formatter.formatDouble(data.getRadiusMin(), 2) + " nm");

    datumPointDatumPanel.setDatumLatMax(data.getDatumMax().getLatitudeAsString());
    datumPointDatumPanel.setDatumLonMax(data.getDatumMax().getLongitudeAsString());
    datumPointDatumPanel.setrdvDistanceMax(Formatter.formatDouble(data.getRdvDistanceMax(), 2) + " nm");
    datumPointDatumPanel.setdatumRadiusMax(Formatter.formatDouble(data.getRadiusMax(), 2) + " nm");

    pointAlat.setText(data.getA().getLatitudeAsString());
    pointAlon.setText(data.getA().getLongitudeAsString());
    pointBlat.setText(data.getB().getLatitudeAsString());
    pointBlon.setText(data.getB().getLongitudeAsString());
    pointClat.setText(data.getC().getLatitudeAsString());
    pointClon.setText(data.getC().getLongitudeAsString());
    pointDlat.setText(data.getD().getLatitudeAsString());
    pointDlon.setText(data.getD().getLongitudeAsString());

    double width = Converter.metersToNm(data.getA().distanceTo(data.getD(), CoordinateSystem.CARTESIAN));
    double height = Converter.metersToNm(data.getB().distanceTo(data.getC(), CoordinateSystem.CARTESIAN));

    areaSize.setText(Formatter.formatDouble(width * height, 2) + " ");
}

From source file:dk.dma.epd.common.prototype.gui.voct.SARPanelCommon.java

License:Apache License

private void setRapidResponseData(RapidResponseData data) {

    CardLayout cl = (CardLayout) (datumPanel.getLayout());
    cl.show(datumPanel, RAPIDRESPONSEDATUM);

    lblSarType.setText("Rapid Response");

    sarData = data;//w w w  .  jav  a  2 s. c o  m

    DateTimeFormatter fmt = DateTimeFormat.forPattern("HH':'mm '-' dd'/'MM");

    lkpDate.setText(fmt.print(data.getLKPDate()));
    cssDateStart.setText(fmt.print(data.getCSSDate()));
    timeElapsed.setText(Formatter.formatHours(data.getTimeElasped()) + "");
    rdvDirection.setText(Formatter.formatDouble(data.getRdvDirection(), 2) + "");
    rdvSpeed.setText(Formatter.formatDouble(data.getRdvSpeed(), 2) + "kn/h");

    rapidResponseDatumPanel.setDatumLat(data.getDatum().getLatitudeAsString());
    rapidResponseDatumPanel.setDatumLon(data.getDatum().getLongitudeAsString());
    rapidResponseDatumPanel.setrdvDistance(Formatter.formatDouble(data.getRdvDistance(), 2) + " nm");
    rapidResponseDatumPanel.setdatumRadius(Formatter.formatDouble(data.getRadius(), 2) + " nm");

    pointAlat.setText(data.getA().getLatitudeAsString());
    pointAlon.setText(data.getA().getLongitudeAsString());
    pointBlat.setText(data.getB().getLatitudeAsString());
    pointBlon.setText(data.getB().getLongitudeAsString());
    pointClat.setText(data.getC().getLatitudeAsString());
    pointClon.setText(data.getC().getLongitudeAsString());
    pointDlat.setText(data.getD().getLatitudeAsString());
    pointDlon.setText(data.getD().getLongitudeAsString());

    areaSize.setText(Formatter.formatDouble(data.getRadius() * 2 * data.getRadius() * 2, 2) + " ");
}