Java Code Examples for org.joda.time.format.PeriodFormatter#print()

The following examples show how to use org.joda.time.format.PeriodFormatter#print() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Helpers.java    From bootstraped-multi-test-results-report with MIT License 6 votes vote down vote up
private Helper<Long> dateHelper() {
    return new Helper<Long>() {
        public CharSequence apply(Long arg0, Options arg1) throws IOException {
            PeriodFormatter formatter = new PeriodFormatterBuilder()
                .appendDays()
                .appendSuffix(" d : ")
                .appendHours()
                .appendSuffix(" h : ")
                .appendMinutes()
                .appendSuffix(" m : ")
                .appendSeconds()
                .appendSuffix(" s : ")
                .appendMillis()
                .appendSuffix(" ms")
                .toFormatter();
            return formatter.print(new Period((arg0 * 1) / 1000000));
        }
    };
}
 
Example 2
Source File: UIUtils.java    From deeplearning4j with Apache License 2.0 6 votes vote down vote up
/**
 * Format the duration in milliseconds to a human readable String, with "yr", "days", "hr" etc prefixes
 *
 *
 * @param durationMs Duration in milliseconds
 * @return Human readable string
 */
public static String formatDuration(long durationMs){
    Period period = Period.seconds((int)(durationMs/1000L));
    Period p2 = period.normalizedStandard(PeriodType.yearMonthDayTime());

    PeriodFormatter formatter = new PeriodFormatterBuilder()
            .appendYears()
            .appendSuffix(" yr ")
            .appendMonths()
            .appendSuffix(" months ")
            .appendDays()
            .appendSuffix(" days ")
            .appendHours()
            .appendSuffix(" hr ")
            .appendMinutes()
            .appendSuffix(" min ")
            .appendSeconds()
            .appendSuffix(" sec")
            .toFormatter();

    return formatter.print(p2);
}
 
Example 3
Source File: DiscordUtil.java    From DiscordBot with Apache License 2.0 5 votes vote down vote up
public static String getTimestamp(long duration) {
	PeriodFormatter periodFormatter = new PeriodFormatterBuilder()
			.appendYears().appendSuffix("y ")
			.appendMonths().appendSuffix("m ")
			.appendWeeks().appendSuffix("w ")
			.appendDays().appendSuffix("d ")
			.appendHours().appendSuffix("h ")
			.appendMinutes().appendSuffix("m ")
			.appendSeconds().appendSuffix("s")
			.toFormatter();
	return periodFormatter.print(new Period(new Duration(duration)).normalizedStandard());
}
 
Example 4
Source File: RRTime.java    From RedReader with GNU General Public License v3.0 5 votes vote down vote up
public static String formatDurationFrom(final Context context, final long startTime) {
	final String space = " ";
	final String comma = ",";
	final String separator = comma + space;

	final long endTime = utcCurrentTimeMillis();
	final DateTime dateTime = new DateTime(endTime);
	final DateTime localDateTime = dateTime.withZone(DateTimeZone.getDefault());
	Period period = new Duration(startTime, endTime).toPeriodTo(localDateTime);

	PeriodFormatter periodFormatter = new PeriodFormatterBuilder()
			.appendYears().appendSuffix(space).appendSuffix(context.getString(R.string.time_year), context.getString(R.string.time_years)).appendSeparator(separator)
			.appendMonths().appendSuffix(space).appendSuffix(context.getString(R.string.time_month), context.getString(R.string.time_months)).appendSeparator(separator)
			.appendDays().appendSuffix(space).appendSuffix(context.getString(R.string.time_day), context.getString(R.string.time_days)).appendSeparator(separator)
			.appendHours().appendSuffix(space).appendSuffix(context.getString(R.string.time_hour), context.getString(R.string.time_hours)).appendSeparator(separator)
			.appendMinutes().appendSuffix(space).appendSuffix(context.getString(R.string.time_min), context.getString(R.string.time_mins)).appendSeparator(separator)
			.appendSeconds().appendSuffix(space).appendSuffix(context.getString(R.string.time_sec), context.getString(R.string.time_secs)).appendSeparator(separator)
			.appendMillis().appendSuffix(space).appendSuffix(context.getString(R.string.time_ms))
			.toFormatter();

	String duration = periodFormatter.print(period.normalizedStandard(PeriodType.yearMonthDayTime()));

	List<String> parts = Arrays.asList(duration.split(comma));
	if (parts.size() >= 2) {
		duration = parts.get(0) + comma + parts.get(1);
	}

	return String.format(context.getString(R.string.time_ago), duration);
}
 
Example 5
Source File: ProgressImpl.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void success() {
  jobExecution.setEndDate(Instant.now());
  jobExecution.setStatus(SUCCESS);
  jobExecution.setProgressInt(jobExecution.getProgressMax());
  Duration yourDuration = Duration.millis(timeRunning());
  Period period = yourDuration.toPeriod();
  PeriodFormatter periodFormatter =
      new PeriodFormatterBuilder()
          .appendDays()
          .appendSuffix("d ")
          .appendHours()
          .appendSuffix("h ")
          .appendMinutes()
          .appendSuffix("m ")
          .appendSeconds()
          .appendSuffix("s ")
          .appendMillis()
          .appendSuffix("ms ")
          .toFormatter();
  String timeSpent = periodFormatter.print(period);
  JOB_EXECUTION_LOG.info("Execution successful. Time spent: {}", timeSpent);
  sendEmail(
      jobExecution.getSuccessEmail(),
      jobExecution.getType() + " job succeeded.",
      jobExecution.getLog());
  update();
  JobExecutionHolder.unset();
}
 
Example 6
Source File: SAXProcessor.java    From SAX with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Generic method to convert the milliseconds into the elapsed time string.
 * 
 * @param start Start timestamp.
 * @param finish End timestamp.
 * @return String representation of the elapsed time.
 */
public static String timeToString(long start, long finish) {

  Duration duration = new Duration(finish - start); // in milliseconds
  PeriodFormatter formatter = new PeriodFormatterBuilder().appendDays().appendSuffix("d")
      .appendHours().appendSuffix("h").appendMinutes().appendSuffix("m").appendSeconds()
      .appendSuffix("s").appendMillis().appendSuffix("ms").toFormatter();

  return formatter.print(duration.toPeriod());

}
 
Example 7
Source File: ValidationLogicImpl.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
private String getFormattedExpirationMinutes() {
	int expirationMinutes = serverConfigurationService.getInt(MAX_PASSWORD_RESET_MINUTES, MAX_PASSWORD_RESET_MINUTES_DEFAULT);
	Period period = new Period(expirationMinutes * 60 * 1000);
	PeriodFormatter periodFormatter = PeriodFormat.wordBased(rl.getLocale());
	return periodFormatter.print(period);
}
 
Example 8
Source File: ValidationLogicImpl.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
private String getFormattedExpirationMinutes() {
	int expirationMinutes = serverConfigurationService.getInt(MAX_PASSWORD_RESET_MINUTES, MAX_PASSWORD_RESET_MINUTES_DEFAULT);
	Period period = new Period(expirationMinutes * 60 * 1000);
	PeriodFormatter periodFormatter = PeriodFormat.wordBased(rl.getLocale());
	return periodFormatter.print(period);
}
 
Example 9
Source File: RunDuration.java    From gocd with Apache License 2.0 4 votes vote down vote up
@Override
public String duration(PeriodFormatter formatter) {
    return formatter.print(duration.toPeriod());
}
 
Example 10
Source File: UptimeMain.java    From cloudhopper-commons with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {

        //Period period = new Period(uptime, PeriodType.standard().withYearsRemoved().withWeeksRemoved().withMonthsRemoved().withMillisRemoved());
        //MutablePeriod period = new Duration(uptime).toPeriod().toMutablePeriod();

        long uptime = UPTIME_56_SECS;

        // ah, ha -- this is super important -- need to normalize the period!
        PeriodType periodType = PeriodType.standard().withYearsRemoved().withMonthsRemoved().withWeeksRemoved().withMillisRemoved();
        Period period = new Period(uptime).normalizedStandard(periodType);

        System.out.println("Uptime: " + uptime + " ms");
        System.out.println("Weeks: " + period.getWeeks());
        System.out.println("Days: " + period.getDays());
        System.out.println("Millis: " + period.getMillis() + " ms");

        // print out the uptime
        String uptimeStyleString = PeriodFormatterUtil.getStandardUptimeStyle().print(period);
        String linuxStyleString = PeriodFormatterUtil.getLinuxUptimeStyle().print(period);

        System.out.println(uptimeStyleString);
        System.out.println(linuxStyleString);

        PeriodFormatter fmt = new PeriodFormatterBuilder()
            .printZeroNever()
            .appendDays()
            .appendSuffix(" day ", " days ")
            .appendHours()
            .appendSuffix(" hours ")
            .appendMinutes()
            .appendSuffix(" mins ")
            .printZeroAlways()
            .appendSeconds()
            .appendSuffix(" secs ")
            .toFormatter();

        String str0 = fmt.print(period);
        System.out.println(str0);


        String str1 = PeriodFormat.getDefault().print(period);
        System.out.println(str1);
    }
 
Example 11
Source File: FormProducer.java    From sakai with Educational Community License v2.0 3 votes vote down vote up
/**
 * Converts some number of minutes into a presentable String'
 * ie for English:
 * 122 minutes  ->      2 hours 2 minutes
 * 121 minutes  ->      2 hours 1 minute
 * 120 minutes  ->      2 hours
 * 62 minutes   ->      1 hour 2 minutes
 * 61 minutes   ->      1 hour 1 minute
 * 60 minutes   ->      1 hour
 * 2 minutes    ->      2 minutes
 * 1 minutes    ->      1 minute
 * 0 minutes    ->      0 minutes
 * Works with other languages too.
 * @param totalMinutes some number of minutes
 * @return a presentable String representation of totalMinutes
 */
public String getFormattedMinutes(int totalMinutes)
{
	// Create a joda time period (takes milliseconds)
	Period period = new Period(totalMinutes*60*1000);
	// format the period for the locale
	/* 
	 * Covers English, Danish, Dutch, French, German, Japanese, Portuguese, and Spanish. 
	 * To translate into others, see http://joda-time.sourceforge.net/apidocs/org/joda/time/format/PeriodFormat.html#wordBased(java.util.Locale)
	 * (ie. put the properties mentioned in http://joda-time.sourceforge.net/apidocs/src-html/org/joda/time/format/PeriodFormat.html#line.94 into the classpath resource bundle)
	 */
	PeriodFormatter periodFormatter = PeriodFormat.wordBased(getLocale());
	return periodFormatter.print(period);
}
 
Example 12
Source File: PasswordResetProducer.java    From sakai with Educational Community License v2.0 3 votes vote down vote up
/**
 * Converts some number of minutes into a presentable String'
 * ie for English:
 * 122 minutes	->	2 hours 2 minutes
 * 121 minutes	->	2 hours 1 minute
 * 120 minutes	->	2 hours
 * 62 minutes	->	1 hour 2 minutes
 * 61 minutes	->	1 hour 1 minute
 * 60 minutes	->	1 hour
 * 2 minutes	->	2 minutes
 * 1 minutes	->	1 minute
 * 0 minutes	->	0 minutes
 * Works with other languages too.
 * @param totalMinutes some number of minutes
 * @return a presentable String representation of totalMinutes
 */
public String getFormattedMinutes(int totalMinutes)
{
	// Create a joda time period (takes milliseconds)
	Period period = new Period(totalMinutes*60*1000);
	// format the period for the locale
	/* 
	 * Covers English, Danish, Dutch, French, German, Japanese, Portuguese, and Spanish. 
	 * To translate into others, see http://joda-time.sourceforge.net/apidocs/org/joda/time/format/PeriodFormat.html#wordBased(java.util.Locale)
	 * (ie. put the properties mentioned in http://joda-time.sourceforge.net/apidocs/src-html/org/joda/time/format/PeriodFormat.html#line.94 into the classpath resource bundle)
	 */
	PeriodFormatter periodFormatter = PeriodFormat.wordBased(getLocale());
	return periodFormatter.print(period);
}
 
Example 13
Source File: AbstractPeriod.java    From astor with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Uses the specified formatter to convert this period to a String.
 *
 * @param formatter  the formatter to use, null means use <code>toString()</code>.
 * @return the formatted string
 * @since 1.5
 */
public String toString(PeriodFormatter formatter) {
    if (formatter == null) {
        return toString();
    }
    return formatter.print(this);
}
 
Example 14
Source File: AbstractPeriod.java    From astor with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Uses the specified formatter to convert this period to a String.
 *
 * @param formatter  the formatter to use, null means use <code>toString()</code>.
 * @return the formatted string
 * @since 1.5
 */
public String toString(PeriodFormatter formatter) {
    if (formatter == null) {
        return toString();
    }
    return formatter.print(this);
}
 
Example 15
Source File: FormProducer.java    From sakai with Educational Community License v2.0 3 votes vote down vote up
/**
 * Converts some number of minutes into a presentable String'
 * ie for English:
 * 122 minutes  ->      2 hours 2 minutes
 * 121 minutes  ->      2 hours 1 minute
 * 120 minutes  ->      2 hours
 * 62 minutes   ->      1 hour 2 minutes
 * 61 minutes   ->      1 hour 1 minute
 * 60 minutes   ->      1 hour
 * 2 minutes    ->      2 minutes
 * 1 minutes    ->      1 minute
 * 0 minutes    ->      0 minutes
 * Works with other languages too.
 * @param totalMinutes some number of minutes
 * @return a presentable String representation of totalMinutes
 */
public String getFormattedMinutes(int totalMinutes)
{
	// Create a joda time period (takes milliseconds)
	Period period = new Period(totalMinutes*60*1000);
	// format the period for the locale
	/* 
	 * Covers English, Danish, Dutch, French, German, Japanese, Portuguese, and Spanish. 
	 * To translate into others, see http://joda-time.sourceforge.net/apidocs/org/joda/time/format/PeriodFormat.html#wordBased(java.util.Locale)
	 * (ie. put the properties mentioned in http://joda-time.sourceforge.net/apidocs/src-html/org/joda/time/format/PeriodFormat.html#line.94 into the classpath resource bundle)
	 */
	PeriodFormatter periodFormatter = PeriodFormat.wordBased(getLocale());
	return periodFormatter.print(period);
}
 
Example 16
Source File: PasswordResetProducer.java    From sakai with Educational Community License v2.0 3 votes vote down vote up
/**
 * Converts some number of minutes into a presentable String'
 * ie for English:
 * 122 minutes	->	2 hours 2 minutes
 * 121 minutes	->	2 hours 1 minute
 * 120 minutes	->	2 hours
 * 62 minutes	->	1 hour 2 minutes
 * 61 minutes	->	1 hour 1 minute
 * 60 minutes	->	1 hour
 * 2 minutes	->	2 minutes
 * 1 minutes	->	1 minute
 * 0 minutes	->	0 minutes
 * Works with other languages too.
 * @param totalMinutes some number of minutes
 * @return a presentable String representation of totalMinutes
 */
public String getFormattedMinutes(int totalMinutes)
{
	// Create a joda time period (takes milliseconds)
	Period period = new Period(totalMinutes*60*1000);
	// format the period for the locale
	/* 
	 * Covers English, Danish, Dutch, French, German, Japanese, Portuguese, and Spanish. 
	 * To translate into others, see http://joda-time.sourceforge.net/apidocs/org/joda/time/format/PeriodFormat.html#wordBased(java.util.Locale)
	 * (ie. put the properties mentioned in http://joda-time.sourceforge.net/apidocs/src-html/org/joda/time/format/PeriodFormat.html#line.94 into the classpath resource bundle)
	 */
	PeriodFormatter periodFormatter = PeriodFormat.wordBased(getLocale());
	return periodFormatter.print(period);
}
 
Example 17
Source File: PeriodConverter.java    From gson-jodatime-serialisers with MIT License 3 votes vote down vote up
/**
 * Gson invokes this call-back method during serialization when it encounters a field of the
 * specified type. <p>
 *
 * In the implementation of this call-back method, you should consider invoking
 * {@link JsonSerializationContext#serialize(Object, Type)} method to create JsonElements for any
 * non-trivial field of the {@code src} object. However, you should never invoke it on the
 * {@code src} object itself since that will cause an infinite loop (Gson will call your
 * call-back method again).
 * @param src the object that needs to be converted to Json.
 * @param typeOfSrc the actual type (fully genericized version) of the source object.
 * @return a JsonElement corresponding to the specified object.
 */
@Override
public JsonElement serialize(Period src, Type typeOfSrc, JsonSerializationContext context)
{
  final PeriodFormatter fmt = ISOPeriodFormat.standard();
  return new JsonPrimitive(fmt.print(src));
}
 
Example 18
Source File: TimeUtil.java    From arcusplatform with Apache License 2.0 3 votes vote down vote up
private static String print(long duration, TimeUnit timeUnit, PeriodFormatter formatter, boolean trim)
{
   Duration durationObject = Duration.millis(timeUnit.toMillis(duration));

   Period normalizedPeriod = durationObject.toPeriod().normalizedStandard();

   String durationString = formatter.print(normalizedPeriod);

   return trim ? durationString.trim() : durationString;
}