Example usage for org.joda.time DateTime toString

List of usage examples for org.joda.time DateTime toString

Introduction

In this page you can find the example usage for org.joda.time DateTime toString.

Prototype

public String toString(String pattern) 

Source Link

Document

Output the instant using the specified format pattern.

Usage

From source file:com.zfer.kit.DateKit.java

License:Apache License

/**
 * ? postDay./* w w  w  .j  a  v a 2 s .c o  m*/
 *
 * @param dateStr like 2014-09-23 ISO8601?
 * @return postDay
 */
public static String getPostDay(String dateStr) {
    if (StrKit.isBlank(dateStr)) {
        return "";
    }
    DateTime dt = new DateTime(dateStr).plusDays(1);
    return dt.toString(DATE_FORMAT);
}

From source file:com.zfer.kit.DateKit.java

License:Apache License

/**
 * ??  2013-02-01./* www .  ja v a2  s.  c o m*/
 *
 * @param dateStr input dateStr
 * @return end of month date
 */
public static String getEndDateOfMonth(String dateStr) {
    DateTime dt = new DateTime(dateStr).dayOfMonth().withMaximumValue();
    return dt.toString(DATE_FORMAT);
}

From source file:course.BlogPostDAO.java

License:Apache License

public String addPost(String title, String body, List tags, String username) {

    System.out.println("inserting blog entry " + title + " " + body);

    String permalink = title.replaceAll("\\s", "_"); // whitespace becomes _
    permalink = permalink.replaceAll("\\W", ""); // get rid of non alphanumeric
    permalink = permalink.toLowerCase();

    // XXX HW 3.2, Work Here
    // Remember that a valid post has the following keys:
    // author, body, permalink, tags, comments, date
    ////from w  ww.  j ava  2s.  c  o  m
    // A few hints:
    // - Don't forget to create an empty list of comments
    // - for the value of the date key, today's datetime is fine.
    // - tags are already in list form that implements suitable interface.
    // - we created the permalink for you above.

    // Build the post object and insert it
    BasicDBObject post = new BasicDBObject();
    post.put("title", title);
    post.put("body", body);
    post.put("tags", tags);
    post.put("author", username);
    post.put("permalink", permalink);
    post.put("comments", new ArrayList<String>());
    DateTime dt = new DateTime();
    post.put("date", dt.toString("MMM d, yyyy h:mm:ss a"));
    postsCollection.insert(post);

    return permalink;
}

From source file:course_generator.resume_table.ResumeHourRenderer.java

License:Open Source License

@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
        int row, int column) {
    super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

    CgResume data = (CgResume) value;/*w  w  w .ja v  a2 s.  c o  m*/

    DateTime val = data.getHour();

    //-- Display the value
    setText(val.toString("E HH:mm:ss "));
    setHorizontalAlignment(CENTER);
    return this;
}

From source file:course_generator.trackdata_table.HourRenderer.java

License:Open Source License

@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
        int row, int column) {
    super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

    TrackData track = (TrackData) value;

    DateTime time = track.data.get(row).getHour();

    //-- Set the value
    setText(time.toString("E HH:mm:ss "));
    setHorizontalAlignment(RIGHT);//  www. ja  v a  2 s .co  m

    //-- Set the background color
    Color c = new Color(221, 255, 155); //Color.LightGreen;

    int ts_val = time.getSecondOfDay();
    int ts_start = track.StartNightTime.getSecondOfDay();
    int ts_end = track.EndNightTime.getSecondOfDay();
    if ((track.bNightCoeff) && ((ts_val > ts_start) || (ts_val < ts_end)))
        c = new Color(0, 128, 255);//95,158,160); //CadetBlue;

    if (isSelected)
        setBackground(new Color(51, 153, 255));
    else
        setBackground(c);

    return this;
}

From source file:course_generator.utils.Utils.java

License:Open Source License

public static String GenLabel(String s, CgData r, TrackData cd, CgSettings settings) {
    /*//from  w  w w.j  ava  2 s . c om
     * %N:Name 
     * %A:Elevation 
     * %D:Distance from the start 
     * %T:Time (hh:mm)
     * %Ts:Time (hh:mm) 
     * %Tl:Time (hh:mm:ss) 
     * %H: Hour (ddd hh:mm) 
     * %h: Hour (hh:mm) 
     * %hs:Hour (hh:mm) 
     * %hl:Hour (hh:mm:s) 
     * %B :Time limit (hh:mm) -> Time from the start 
     * %b :Time limit (hh:mm) -> Limit hour 
     * %C :Comment
     * %c :Comment from the main data 
     * %L :Carriage return 
     * %R :Station time (hh:mm) 
     * %Rs:Station time (hh:mm) 
     * %Rl:Station time (Duration) (hh:mm:ss) 
     * %+ :Sum ascend 
     * %- :Sum descend
     */
    int i = 0;
    int step = 0;
    String sr = "";
    DateTime dt;

    if (cd != null) {
        CalcClimbResult res = new CalcClimbResult();
        res = cd.CalcClimb(0, (int) (r.getNum() - 1), res);

        for (i = 0; i < s.length(); i++) {
            switch (step) {
            case 0: {
                if (s.charAt(i) == '%') {
                    step = 1;
                } else {
                    sr = sr + s.charAt(i);
                }
                break;
            }
            case 1: {
                switch (s.charAt(i)) {
                // %N:Name
                case 'N':
                    sr = sr + r.getName();
                    step = 0;
                    break;

                // A:Elevation
                case 'A':
                    sr = sr + String.format("%.0f", r.getElevation(settings.Unit));
                    step = 0;
                    break;

                // %D:Distance from the start
                case 'D':
                    sr = sr + String.format("%.1f", r.getTotal(settings.Unit) / 1000.0);
                    step = 0;
                    break;

                // %T:Time (hh:mm)
                case 'T':
                    step = 3;
                    break;

                // %H:Hour (ddd hh:mm)
                case 'H':
                    sr = sr + r.getHour().toString("E HH:mm");
                    step = 0;
                    break;

                // %h:Time (hh:mm)
                case 'h':
                    step = 2;
                    break;

                // %R:Station time (hh:mm:ss)
                case 'R':
                    step = 4;
                    break;

                // %B:Time limit (hh:mm) -> Time from the start
                case 'B':
                    sr = sr + Utils.Second2DateString_HM(r.getTimeLimit());
                    step = 0;
                    break;

                // %b:Time limit (hh:mm) -> Limit hour
                case 'b':
                    if (cd != null) {
                        dt = cd.StartTime.plusSeconds(r.getTimeLimit());
                        sr = sr + dt.toString("HH:mm");
                    } else {
                        sr = sr + "00:00";
                    }
                    step = 0;
                    break;

                // %C:Comment from the MRB data
                case 'C':
                    sr = sr + r.CommentMiniRoadbook;
                    step = 0;
                    break;

                // %c:Comment from the main data
                case 'c':
                    sr = sr + r.getComment();
                    step = 0;
                    break;

                // %+: Sum ascend
                case '+':
                    sr = sr + String.format("%.0f", res.cp);
                    step = 0;
                    break;

                // %-: Sum descend
                case '-':
                    sr = sr + String.format("%.0f", res.cm);
                    step = 0;
                    break;

                // %L: Carriage return
                case 'L':
                    sr = sr + "\n";
                    step = 0;
                    break;

                default:
                    sr = sr + s.charAt(i);
                    break;
                }
                break;
            }

            case 2: // %h
            {
                switch (s.charAt(i)) {
                case 's':
                    sr = sr + r.getHour().toString("HH:mm");
                    step = 0;
                    break;
                case 'l':
                    sr = sr + r.getHour().toString("HH:mm:ss");
                    step = 0;
                    break;
                default:
                    sr = sr + r.getHour().toString("HH:mm");
                    sr = sr + s.charAt(i);
                    step = 0;
                    break;
                }
                break;
            }

            case 3: // %T
            {
                switch (s.charAt(i)) {
                case 's':
                    sr = sr + Utils.Second2DateString_HM(r.getTime());
                    step = 0;
                    break;
                case 'l':
                    sr = sr + Utils.Second2DateString(r.getTime());
                    step = 0;
                    break;
                default:
                    sr = sr + Utils.Second2DateString_HM(r.getTime());
                    sr = sr + s.charAt(i);
                    step = 0;
                    break;
                }
                break;
            }

            case 4: // %R
            {
                switch (s.charAt(i)) {
                case 's':
                    sr = sr + Utils.Second2DateString_HM(r.getStation());
                    step = 0;
                    break;
                case 'l':
                    sr = sr + Utils.Second2DateString(r.getStation());
                    step = 0;
                    break;
                default:
                    sr = sr + Utils.Second2DateString(r.getStation());
                    sr = sr + s.charAt(i);
                    step = 0;
                    break;
                }
                break;
            }

            }
        }

        // Manage a command if it's the last character
        // If a command with 1 or 2 characters => Default value
        if (step == 2) {
            sr = sr + r.getHour().toString("HH:mm");
        } else if (step == 3) {
            sr = sr + Utils.Second2DateString_HM(r.getTime());
        } else if (step == 4) {
            sr = sr + Utils.Second2DateString(r.getStation());
        }

        if (cd != null) {
            return Utils.WordWrap(sr, cd.WordWrapLength, true);
        }
        // else {
        // return sr;
        // }
    }
    return sr;
}

From source file:ddf.metrics.plugin.webconsole.MetricsWebConsolePlugin.java

License:Open Source License

private static String urlEncodeDate(DateTime date) throws UnsupportedEncodingException {
    return URLEncoder.encode(date.toString(ISODateTimeFormat.dateTimeNoMillis()), CharEncoding.UTF_8);
}

From source file:ddf.metrics.reporting.internal.rrd4j.RrdMetricsRetriever.java

License:Open Source License

private void createSummary(Workbook wb, List<String> metricNames, String metricsDir, long startTime,
        long endTime, SUMMARY_INTERVALS summaryInterval) throws IOException, MetricsGraphException {
    // convert seconds to milliseconds
    startTime = TimeUnit.SECONDS.toMillis(startTime);
    endTime = TimeUnit.SECONDS.toMillis(endTime);
    DateTime reportStart = new DateTime(startTime, DateTimeZone.UTC);
    DateTime reportEnd = new DateTime(endTime, DateTimeZone.UTC);

    Sheet sheet = wb.createSheet();// w  ww . ja v a  2 s  .com
    wb.setSheetName(0,
            reportStart.toString(SUMMARY_TIMESTAMP) + " to " + reportEnd.toString(SUMMARY_TIMESTAMP));
    Row headingRow = sheet.createRow(0);

    int columnMax = 1;
    for (String metricName : metricNames) {
        MutableDateTime chunkStart = new MutableDateTime(reportStart);
        MutableDateTime chunkEnd = new MutableDateTime(chunkStart);
        Row row = sheet.createRow(metricNames.indexOf(metricName) + 1);
        int columnCounter = 1;
        Boolean isSum = null;

        while (reportEnd.compareTo(chunkEnd) > 0 && columnCounter < EXCEL_MAX_COLUMNS) {
            increment(chunkEnd, summaryInterval);
            if (chunkEnd.isAfter(reportEnd)) {
                chunkEnd.setMillis(reportEnd);
            }

            // offset range by one millisecond so rrd will calculate granularity correctly
            chunkEnd.addMillis(-1);
            MetricData metricData = getMetricData(getRrdFilename(metricsDir, metricName),
                    TimeUnit.MILLISECONDS.toSeconds(chunkStart.getMillis()),
                    TimeUnit.MILLISECONDS.toSeconds(chunkEnd.getMillis()));
            isSum = metricData.hasTotalCount();
            chunkEnd.addMillis(1);

            if (headingRow.getCell(columnCounter) == null) {
                Cell headingRowCell = headingRow.createCell(columnCounter);
                headingRowCell.getCellStyle().setWrapText(true);
                headingRowCell.setCellValue(getTimestamp(chunkStart, chunkEnd, columnCounter, summaryInterval));
            }

            Cell sumOrAvg = row.createCell(columnCounter);
            if (isSum) {
                sumOrAvg.setCellValue((double) metricData.getTotalCount());
            } else {
                sumOrAvg.setCellValue(cumulativeRunningAverage(metricData.getValues()));
            }

            chunkStart.setMillis(chunkEnd);
            columnCounter++;
        }
        columnMax = columnCounter;

        if (isSum != null) {
            row.createCell(0).setCellValue(convertCamelCase(metricName) + " (" + (isSum ? "sum" : "avg") + ")");
        }
    }
    for (int i = 0; i < columnMax; i++) {
        sheet.autoSizeColumn(i);
    }
}

From source file:de.dbload.csv.writer.ResourceWriter.java

License:Apache License

public void start(Connection conn, String sqlSelect, boolean append) throws SQLException {

    if (append) {
        if (!file.exists()) {
            try {
                file.createNewFile();// www  .  ja  v a2  s  .  c  o m
            } catch (IOException ex) {
                throw new DbloadException("Unable to create export file.", ex);
            }
        }
    } else {
        if (file.exists()) {
            file.delete();
        }
    }

    try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(file.toPath(),
            append ? StandardOpenOption.APPEND : StandardOpenOption.CREATE));
            Writer writer = new OutputStreamWriter(out, utf8)) {

        PrintWriter pw = new PrintWriter(writer, true);
        try (Statement stmt = conn.createStatement(); ResultSet resultSet = stmt.executeQuery(sqlSelect)) {

            ResultSetMetaData metaData = resultSet.getMetaData();

            pw.print("### TAB ");
            pw.println(metaData.getTableName(1));
            pw.print("### ");

            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                pw.print(metaData.getColumnName(i));
                if (i < metaData.getColumnCount()) {
                    pw.print(" | ");
                }
            }
            pw.println();

            while (resultSet.next()) {
                for (int i = 1; i <= metaData.getColumnCount(); i++) {

                    String print = null;
                    int type = resultSet.getMetaData().getColumnType(i);
                    Type columnType = ColumnMetaData.Type.valueOf(type);
                    switch (columnType) {
                    case DATE:
                    case TIME:
                    case DATE_TIME:
                        Timestamp timestamp = resultSet.getTimestamp(i);
                        if (timestamp == null) {
                            print = "";
                        } else {
                            Date date = new Date(timestamp.getTime());
                            DateTime dateTime = new DateTime(date);
                            print = dateTime.toString(DateTimeUtils.DATE_FORMAT);
                        }
                        break;
                    default:
                        print = resultSet.getString(i);
                    }

                    if (print == null) {
                        pw.print("");
                    } else {
                        pw.print(print);
                    }

                    if (i < metaData.getColumnCount()) {
                        pw.print(" | ");
                    }
                }
                pw.println();
            }
            pw.println();
        }
    } catch (IOException ex) {
        throw new DbloadException(ex);
    }
}

From source file:de.dmarcini.submatix.android4.full.gui.SPX42ReadLogFragment.java

License:Open Source License

  /**
 * //from   w  w w  . j a v  a 2 s.  co  m
 * Bearbeite die Nachricht ber einen Logeintrag
 * 
 * Project: SubmatixBTLoggerAndroid_4 Package: de.dmarcini.submatix.android4.gui
 * 
 * 
 * Stand: 06.08.2013
 * 
 * @param msg
 */
private void msgComputeDirentry( BtServiceMessage msg )
{
  // Fields
  // 0 => Nummer
  // 1 => Filename
  // 2 => Max Nummer
  String[] fields;
  String fileName;
  int dbId = -1;
  String detailText;
  int number, max;
  int day, month, year, hour, minute, second;
  boolean isSaved = false;
  Resources res = runningActivity.getResources();
  //
  if( !( msg.getContainer() instanceof String[] ) )
  {
    Log.e( TAG, "Message container not an String ARRAY!" );
    return;
  }
  fields = ( String[] )msg.getContainer();
  if( fields.length < 3 )
  {
    Log.e( TAG, "recived message for logdir has lower than 3 fields. It is wrong! Abort!" );
    return;
  }
  // Wandel die Nummerierung in Integer um
  try
  {
    number = Integer.parseInt( fields[0], 16 );
    max = Integer.parseInt( fields[2], 16 );
  }
  catch( NumberFormatException ex )
  {
    Log.e( TAG, "Fail to convert Hex to int: " + ex.getLocalizedMessage() );
    return;
  }
  // Alles gelesen: Fertich
  if( number == max )
  {
    countDirEntrys = 0;
    if( pd != null )
    {
      pd.dismiss();
    }
    return;
  }
  fileName = fields[1];
  // verwandle die Dateiangabe in eine lesbare Datumsangabe
  // Format des Strings ist ja
  // TAG_MONAT_JAHR_STUNDE_MINUTE_SEKUNDE
  // des Beginns der Aufzeichnung
  fields = fieldPatternUnderln.split( fields[1] );
  try
  {
    day = Integer.parseInt( fields[0] );
    month = Integer.parseInt( fields[1] );
    year = Integer.parseInt( fields[2] ) + 2000;
    hour = Integer.parseInt( fields[3] );
    minute = Integer.parseInt( fields[4] );
    second = Integer.parseInt( fields[5] );
  }
  catch( NumberFormatException ex )
  {
    Log.e( TAG, "Fail to convert Hex to int: " + ex.getLocalizedMessage() );
    return;
  }
  // So, die Angaben des SPX sind immer im Localtime-Format
  // daher werde ich die auch so interpretieren
  // Die Funktion macht das in der default-Lokalzone, sollte also
  // da sein, wo der SPX auch ist... (schwieriges Thema)
  DateTime tm = new DateTime( year, month, day, hour, minute, second );
  //
  // Jetzt ist der Zeitpunkt, die Datenbank zu befragen, ob das Logteilchen schon gesichert ist
  //
  isSaved = logManager.isLogInDatabase( FragmentCommonActivity.spxConfig.getSerial(), fileName );
  if( isSaved )
  {
    if( showAllLogEntrys )
    {
      SPX42DiveHeadData diveHead = logManager.getDiveHeader( FragmentCommonActivity.spxConfig.getSerial(), fileName );
      detailText = makeDetailText( diveHead );
      dbId = diveHead.diveId;
      //
      // jetzt eintagen in die Anzeige
      //
      ReadLogItemObj rlio = new ReadLogItemObj( isSaved, String.format( "#%03d: %s", number, tm.toString( FragmentCommonActivity.localTimeFormatter ) ), fileName, detailText,
              dbId, number, tm.getMillis() );
      // Eintrag an den Anfang stellen
      logListAdapter.insert( rlio, 0 );
    }
    else
    {
      if( ApplicationDEBUG.DEBUG ) Log.i( TAG, "ignore saved log while \"show all logitems\" is not set..." );
    }
  }
  else
  {
    detailText = res.getString( R.string.logread_not_saved_yet_msg );
    //
    // jetzt eintagen in die Anzeige
    //
    ReadLogItemObj rlio = new ReadLogItemObj( isSaved, String.format( "#%03d: %s", number, tm.toString( FragmentCommonActivity.localTimeFormatter ) ), fileName, detailText,
            dbId, number, tm.getMillis() );
    // Eintrag an den Anfang stellen
    logListAdapter.insert( rlio, 0 );
  }
  if( pd != null )
  {
    pd.setMessage( String.format( runningActivity.getResources().getString( R.string.logread_please_wait_dialog_directory ), ++countDirEntrys ) );
  }
}