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:com.esofthead.mycollab.shell.view.SetupNewInstanceView.java

License:Open Source License

private boolean isValidDayPattern(String dateFormat) {
    try {//from   w  w  w.ja v a  2 s  .  c o  m
        DateTimeFormatter formatter = DateTimeFormat.forPattern(dateFormat);
        formatter.print(new DateTime());
        return true;
    } catch (Exception e) {
        return false;
    }
}

From source file:com.esofthead.mycollab.vaadin.AppContext.java

License:Open Source License

/**
 * @param date is the UTC date value/*from  w  w  w  . j ava  2  s.  co m*/
 * @return
 */
public static String formatDateTime(Date date) {
    //        return date == null ? "" : DateTimeUtils.formatDate(date, AppContext.getDateTimeFormat(), AppContext.getUserTimeZone());
    if (date == null) {
        return "";
    } else {
        DateTime jodaDate = new DateTime(date)
                .toDateTime(DateTimeZone.forTimeZone(AppContext.getUserTimeZone()));
        if (jodaDate.getHourOfDay() > 0 || jodaDate.getMinuteOfHour() > 0) {
            DateTimeFormatter formatter = DateTimeFormat.forPattern(AppContext.getDateTimeFormat());
            return formatter.print(jodaDate);
        } else {
            DateTimeFormatter formatter = DateTimeFormat.forPattern(AppContext.getDateFormat());
            return formatter.print(jodaDate);
        }
    }
}

From source file:com.evolveum.midpoint.wf.impl.processors.BaseModelInvocationProcessingHelper.java

License:Apache License

/**
 * Determines the root task name (e.g. "Workflow for adding XYZ (started 1.2.2014 10:34)")
 * TODO allow change processor to influence this name
 */// w  w  w .  j  a  v a2  s . c o m
private String determineRootTaskName(ModelContext context) {

    String operation;
    if (context.getFocusContext() != null && context.getFocusContext().getPrimaryDelta() != null
            && context.getFocusContext().getPrimaryDelta().getChangeType() != null) {
        switch (context.getFocusContext().getPrimaryDelta().getChangeType()) {
        case ADD:
            operation = "creation of";
            break;
        case DELETE:
            operation = "deletion of";
            break;
        case MODIFY:
            operation = "change of";
            break;
        default:
            throw new IllegalStateException();
        }
    } else {
        operation = "change of";
    }
    String name = MiscDataUtil.getFocusObjectName(context);

    DateTimeFormatter formatter = DateTimeFormat.forStyle("MM").withLocale(Locale.getDefault());
    String time = formatter.print(System.currentTimeMillis());

    //        DateFormat dateFormat = DateFormat.getDateTimeInstance();
    //        String time = dateFormat.format(new Date());

    return "Approving and executing " + operation + " " + name + " (started " + time + ")";
}

From source file:com.example.ashwin.popularmovies.FetchMovieTask.java

License:Apache License

protected Void doInBackground(String... params) {
    if (params.length == 0) {
        return null;
    }/*from  w w  w  .j  ava2  s.  c o m*/
    // needs to be outside try catch to use in finally
    HttpURLConnection urlConnection = null;
    BufferedReader reader = null;

    // will contain the raw JSON response as a string
    String movieJsonStr = null;
    try {
        // http://api.themoviedb.org/3/discover/movie?sort_by=popularity.desc&api_key=**REMOVED**
        Uri.Builder builder = new Uri.Builder();
        builder.scheme("http").authority("api.themoviedb.org").appendPath("3").appendPath("discover")
                .appendPath("movie");
        if (params[0].equals(mContext.getString(R.string.pref_sort_label_upcoming))) {
            // so here we need to get today's date and 3 weeks from now
            DateTime todayDt = new DateTime();
            DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd");
            String todayDateString = fmt.print(todayDt);
            builder.appendQueryParameter("primary_release_date.gte", todayDateString);

            // 3 weeks from now
            DateTime dtPlusTwoWeeks = todayDt.plusWeeks(3);
            String twoWeeksLaterDate = fmt.print(dtPlusTwoWeeks);
            builder.appendQueryParameter("primary_release_date.lte", twoWeeksLaterDate);
        } else {
            builder.appendQueryParameter("sort_by", params[0]);

            // here we need to get a minimum vote count, value is set to 200 minimum votes
            if (params[0].equals(mContext.getString(R.string.pref_sort_user_rating)))
                builder.appendQueryParameter("vote_count.gte", "200");
        }
        builder.appendQueryParameter("api_key", mContext.getString(R.string.tmdb_api_key));

        String website = builder.build().toString();
        URL url = new URL(website);

        // Create the request to themoviedb and open connection
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.connect();

        // Read the input stream into a string
        InputStream inputStream = urlConnection.getInputStream();
        StringBuffer buffer = new StringBuffer();
        if (inputStream == null) {
            // nothing to do
            return null;
        }
        reader = new BufferedReader(new InputStreamReader(inputStream));

        String line;
        while ((line = reader.readLine()) != null) {
            // doesn't affect JSON but it's a lot easier for a human to read
            buffer.append(line + "\n");
        }

        if (buffer.length() == 0) {
            // empty stream
            return null;
        }
        movieJsonStr = buffer.toString();
    } catch (IOException e) {
        Log.e(LOG_TAG, "Error closing stream", e);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
        if (reader != null) {
            try {
                reader.close();
            } catch (final IOException e) {
                Log.e(LOG_TAG, "Error closing stream", e);
            }
        }
    }

    try {
        getMovieDataFromJsonDb(movieJsonStr);
    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        e.printStackTrace();
    }
    return null;
}

From source file:com.example.bigquery.QueryParametersSample.java

License:Apache License

private static void runTimestamp() throws InterruptedException {
    BigQuery bigquery = new BigQueryOptions.DefaultBigqueryFactory()
            .create(BigQueryOptions.getDefaultInstance());

    DateTime timestamp = new DateTime(2016, 12, 7, 8, 0, 0, DateTimeZone.UTC);

    String queryString = "SELECT TIMESTAMP_ADD(@ts_value, INTERVAL 1 HOUR);";
    QueryRequest queryRequest = QueryRequest.newBuilder(queryString)
            .addNamedParameter("ts_value", QueryParameterValue.timestamp(
                    // Timestamp takes microseconds since 1970-01-01T00:00:00 UTC
                    timestamp.getMillis() * 1000))
            // Standard SQL syntax is required for parameterized queries.
            // See: https://cloud.google.com/bigquery/sql-reference/
            .setUseLegacySql(false).build();

    // Execute the query.
    QueryResponse response = bigquery.query(queryRequest);

    // Wait for the job to finish (if the query takes more than 10 seconds to complete).
    while (!response.jobCompleted()) {
        Thread.sleep(1000);/*from  www.j  ava  2s. c om*/
        response = bigquery.getQueryResults(response.getJobId());
    }

    if (response.hasErrors()) {
        throw new RuntimeException(response.getExecutionErrors().stream().<String>map(err -> err.getMessage())
                .collect(Collectors.joining("\n")));
    }

    QueryResult result = response.getResult();
    Iterator<List<FieldValue>> iter = result.iterateAll();

    DateTimeFormatter formatter = ISODateTimeFormat.dateTimeNoMillis().withZoneUTC();
    while (iter.hasNext()) {
        List<FieldValue> row = iter.next();
        System.out.printf("%s\n", formatter.print(new DateTime(
                // Timestamp values are returned in microseconds since 1970-01-01T00:00:00 UTC,
                // but org.joda.time.DateTime constructor accepts times in milliseconds.
                row.get(0).getTimestampValue() / 1000, DateTimeZone.UTC)));
    }
}

From source file:com.example.Database.java

public String getDate(int daysago) {
    DateTime date = new DateTime();
    DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd");
    date = date.minusDays(daysago);/*from w  ww.  j a v  a2s  .  co  m*/
    return fmt.print(date);
}

From source file:com.facebook.presto.operator.scalar.DateTimeFunctions.java

License:Apache License

private static Slice formatDatetime(ISOChronology chronology, Locale locale, long timestamp,
        Slice formatString) {/*  w  w w  .j  a v  a2  s .  c  o  m*/
    String pattern = formatString.toString(Charsets.UTF_8);
    DateTimeFormatter formatter = DateTimeFormat.forPattern(pattern).withChronology(chronology)
            .withLocale(locale);

    String datetimeString = formatter.print(timestamp);
    return Slices.wrappedBuffer(datetimeString.getBytes(Charsets.UTF_8));
}

From source file:com.facebook.presto.operator.scalar.DateTimeFunctions.java

License:Apache License

private static Slice dateFormat(ISOChronology chronology, Locale locale, long timestamp, Slice formatString) {
    DateTimeFormatter formatter = DATETIME_FORMATTER_CACHE.get(formatString).withChronology(chronology)
            .withLocale(locale);/*www  . java 2 s  .  c  o m*/

    return Slices.copiedBuffer(formatter.print(timestamp), Charsets.UTF_8);
}

From source file:com.facebook.presto.operator.scalar.UnixTimeFunctions.java

License:Apache License

@Description("formats the given time by the given format")
@ScalarFunction/*  w w  w . j  av  a  2  s . c  o  m*/
public static Slice formatDatetime(long unixTime, Slice formatString) {
    String pattern = formatString.toString(Charsets.UTF_8);
    DateTimeFormatter formatter = DateTimeFormat.forPattern(pattern).withZoneUTC();

    String datetimeString = formatter.print(toMillis(unixTime));
    return Slices.wrappedBuffer(datetimeString.getBytes(Charsets.UTF_8));
}

From source file:com.facebook.presto.operator.scalar.UnixTimeFunctions.java

License:Apache License

@ScalarFunction
public static Slice dateFormat(long unixTime, Slice formatString) {
    DateTimeFormatter formatter = DATETIME_FORMATTER_CACHE.get(formatString);
    return Slices.copiedBuffer(formatter.print(toMillis(unixTime)), Charsets.UTF_8);
}