Example usage for java.text SimpleDateFormat setTimeZone

List of usage examples for java.text SimpleDateFormat setTimeZone

Introduction

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

Prototype

public void setTimeZone(TimeZone zone) 

Source Link

Document

Sets the time zone for the calendar of this DateFormat object.

Usage

From source file:KunderPackage.KunderClass.java

@GET
@Path("/time")
public Response time(@QueryParam("value") String value) throws JSONException {
    try {//from   w  ww .  jav  a2 s .c o  m
        //Expresion regular valida, modificar en caso de agregar nuevas
        // expresiones regulares.
        String expresionValida = "hora";

        //Descomentar si se desea desactivar tipado fuerte para variable value
        // as valores como hora, Hora, hOra, HOra, etc... seran validos
        //value = value.toUpperCase();
        //expresionValida = expresionValida.toUpperCase();

        //Define el formato que debe tener la variable value
        Pattern expresionRegular = Pattern.compile(expresionValida);
        Matcher valorEvaluar = expresionRegular.matcher(value);
        String mensaje = "";

        if (valorEvaluar.matches()) {
            //Obtenemos la fecha en formato UTC
            Date fecha = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("EEE, MMM d, yyyy hh:mm:ss a z");
            sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

            //Se crea el JSON de respuesta
            JSONObject rs = new JSONObject();
            rs.put("code", "00");
            rs.put("description", "OK");
            rs.put("data", sdf.format(fecha));

            // Se retorna una respuesta con el json y el valor status 200
            return Response.ok(rs.toString(), MediaType.APPLICATION_JSON).build();
        }
        // Error si es que la variable no fue enviada o fue enviada en blanco.
        else if (value.isEmpty()) {
            mensaje = "Error 400, debe especificar la variable 'value'.";
        }
        //Error si variable contiene algun valor no aceptado.
        else if (!value.isEmpty()) {
            mensaje = "Error 400, valor '" + value + "' no soportado.";
        }
        return Response.status(400).entity(mensaje).build();
    }
    //Retorna error 500 si ocurre algo en tiempo de ejecucin.
    catch (Exception e) {
        return Response.serverError().entity(e).build();
    }
}

From source file:io.cloudslang.content.amazon.services.helpers.AwsSignatureHelper.java

/**
 * Converts a java.util.Date to an AWS specific date format.
 * The AWS date should be in (java) format "yyyyMMdd'T'HHmmss'Z'" and in time zone UTC.
 *
 * @param date Date to be formatted.// www  .j  av  a 2 s  . c  o  m
 * @return A string representing the formatted date.
 */
public String getAmazonDateString(Date date) {
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DATE_FORMAT);
    simpleDateFormat.setTimeZone(TimeZone.getTimeZone(TIME_ZONE));
    return simpleDateFormat.format(date);
}

From source file:com.bc.amazon.HmacSecurityHandler.java

/**
 * Calculates a time stamp from "now" in UTC and returns it in ISO8601 string
 * format. The soap message expires 15 minutes after this time stamp.
 * AWS only supports UTC and it's canonical representation as 'Z' in an
 * ISO8601 time string. E.g.  2008-02-10T23:59:59Z
 * /*  w  ww .  j a v a  2  s .  c o m*/
 * See http://www.w3.org/TR/xmlschema-2/#dateTime for more details.
 * 
 * @return ISO8601 time stamp string for "now" in UTC.
 */
private String getTimestamp() {
    Calendar calendar = Calendar.getInstance();
    SimpleDateFormat is08601 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");

    is08601.setTimeZone(TimeZone.getTimeZone("UTC"));
    return is08601.format(calendar.getTime());
}

From source file:com.cimpoint.mes.server.repositories.UnitRepository.java

public String getTimeDecoder(Date clientTime, String clientTimezoneId) {
    SimpleDateFormat timeFormater = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
    timeFormater.setTimeZone(TimeZone.getTimeZone("UTC"));
    String utcTime = timeFormater.format(clientTime);
    return "UTC-" + utcTime + "-" + clientTimezoneId;
}

From source file:com.adaptris.core.services.metadata.DateFormatBuilder.java

private DateFormatter withTimeZone(SimpleDateFormat format, String id) {
    format.setTimeZone((!isBlank(id)) ? TimeZone.getTimeZone(id) : TimeZone.getDefault());
    return new SimpleDateFormatter(format);
}

From source file:net.asfun.jangod.lib.filter.DatetimeFilter.java

@Override
public Object filter(Object object, JangodInterpreter interpreter, String... arg) throws InterpretException {
    if (object == null) {
        return object;
    }//ww w.  java  2s  . c  o m
    if (object instanceof DateTime) { // joda DateTime
        DateTimeFormatter formatter;
        DateTimeFormatter a = DateTimeFormat.forPattern(interpreter.evaluateExpressionAsString(arg[0]));
        if (arg.length == 1) {
            DateTimeFormatter forPattern = a;
            JodaTimeContext jodaTimeContext = JodaTimeContextHolder.getJodaTimeContext();
            if (jodaTimeContext == null) {
                jodaTimeContext = new JodaTimeContext();
            }
            formatter = jodaTimeContext.getFormatter(forPattern);
        } else if (arg.length == 2) {
            formatter = a.withChronology(ISOChronology
                    .getInstance(DateTimeZone.forID(interpreter.evaluateExpressionAsString(arg[1]))));
        } else {
            throw new InterpretException("filter date expects 1 or 2 args >>> " + arg.length);
        }
        return formatter.print((DateTime) object);
    } else {
        SimpleDateFormat sdf;
        if (arg.length == 1) {
            sdf = new SimpleDateFormat(interpreter.evaluateExpressionAsString(arg[0]));
            sdf.setTimeZone(interpreter.getConfiguration().getTimezone());
        } else if (arg.length == 2) {
            sdf = new SimpleDateFormat(interpreter.evaluateExpressionAsString(arg[0]));
            sdf.setTimeZone(TimeZone.getTimeZone(interpreter.evaluateExpressionAsString(arg[1])));
        } else {
            throw new InterpretException("filter date expects 1 or 2 args >>> " + arg.length);
        }
        return sdf.format(object);
    }
}

From source file:com.alibaba.rocketmq.tools.command.cluster.CLusterSendMsgRTCommand.java

public String getCurTime() {
    String fromTimeZone = "GMT+8";

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date date = new Date();
    format.setTimeZone(TimeZone.getTimeZone(fromTimeZone));
    String chinaDate = format.format(date);
    return chinaDate;
}

From source file:com.amazon.advertising.api.common.HmacSecurityHandler.java

/**
 * Calculates a time stamp from "now" in UTC and returns it in ISO8601 string
 * format. The soap message expires 15 minutes after this time stamp.
 * AWS only supports UTC and it's canonical representation as 'Z' in an
 * ISO8601 time string. E.g.  2008-02-10T23:59:59Z
 * <p/>/*from   w w  w  .  j  a v a 2s. c o m*/
 * See http://www.w3.org/TR/xmlschema-2/#dateTime for more details.
 *
 * @return ISO8601 time stamp string for "now" in UTC.
 */
public String getTimestamp() {
    Calendar calendar = Calendar.getInstance();
    SimpleDateFormat is08601 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");

    is08601.setTimeZone(TimeZone.getTimeZone("UTC"));
    return is08601.format(calendar.getTime());
}

From source file:com.sonoport.freesound.response.mapping.Mapper.java

/**
 * Parse a date from a {@link String} to a {@link Date} object, assuming the freesound standard format.
 *
 * @param dateString The string to convert
 * @return {@link Date} representation/*w  w  w. j  a  va2  s.  com*/
 */
protected Date parseDate(final String dateString) {
    Date date = null;
    if (dateString != null) {
        try {
            final SimpleDateFormat dateFormat = new SimpleDateFormat(FREESOUND_DATE_FORMAT);
            dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));

            date = dateFormat.parse(dateString);
        } catch (final ParseException e) {
            // TODO Log a warning
        }
    }

    return date;
}

From source file:com.flurry.samples.analytics.PhotoDetailActivity.java

/**
     * Load Photo Details into View. Load photo from Picasso into View.
     */* w w w .  jav a 2  s . co m*/
     * @param photo    Photo object
     */
    public void loadPhotoDetails(final Photo photo) {

        flickrClient = new FlickrClient();

        HashMap<String, String> fetchPhotoStatEventParams = new HashMap<>(2);
        fetchPhotoStatEventParams.put(AnalyticsHelper.PARAM_FETCH_PHOTO_ID, String.valueOf(photo.getPhotoId()));
        fetchPhotoStatEventParams.put(AnalyticsHelper.PARAM_FETCH_PHOTO_SECRET, String.valueOf(photo.getSecret()));
        AnalyticsHelper.logEvent(AnalyticsHelper.EVENT_FETCH_PHOTO_STATS, fetchPhotoStatEventParams, true);

        Log.i(LOG_TAG, "Logging event: " + AnalyticsHelper.EVENT_FETCH_PHOTO_STATS);

        flickrClient.getPhotoDetailFeed(photo.getPhotoId(), photo.getSecret(), new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int code, Header[] headers, JSONObject body) {

                AnalyticsHelper.endTimedEvent(AnalyticsHelper.EVENT_FETCH_PHOTO_STATS);

                if (body != null) {
                    try {
                        photo.setOwner(body.getJSONObject("photo").getJSONObject("owner").getString("realname"));
                        photo.setDateTaken(body.getJSONObject("photo").getJSONObject("dates").getString("taken"));

                        long datePosted = Long
                                .parseLong(body.getJSONObject("photo").getJSONObject("dates").getString("posted"));
                        Date date = new Date(datePosted * 1000L);
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        sdf.setTimeZone(TimeZone.getTimeZone("GMT-8"));

                    } catch (JSONException e) {
                        AnalyticsHelper.logError(LOG_TAG, "Deserialize photo detail JSONObject error.", e);
                    }

                } else {
                    AnalyticsHelper.logError(LOG_TAG, "Response body is null", null);
                }

                if (photo.getTitle() != null && !photo.getTitle().trim().equals("")) {
                    title.setText(photo.getTitle());
                }
                if (photo.getOwner() != null && !photo.getOwner().trim().equals("")) {
                    owner.setText(Html.fromHtml("<b>By </b> " + photo.getOwner()));
                }

                if (photo.getDateTaken() != null && !photo.getDateTaken().trim().equals("")) {
                    dateTaken.setText(Html.fromHtml("<b>Taken On </b> " + photo.getDateTaken().split(" ")[0]));
                }

                Picasso.with(PhotoDetailActivity.this).load(photo.getPhotoUrl()).error(R.drawable.noimage)
                        .placeholder(R.drawable.noimage).into(photoImage);
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                AnalyticsHelper.logError(LOG_TAG, "Failure in fetching photo details", null);
                super.onFailure(statusCode, headers, responseString, throwable);
            }
        });
    }