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:com.tenmiles.helpstack.gears.HSHappyfoxGear.java

private static Date parseUTCString(String timeStr, String pattern) throws ParseException {
    SimpleDateFormat format = new SimpleDateFormat(pattern, Locale.getDefault());
    format.setTimeZone(TimeZone.getTimeZone("UTC"));
    return format.parse(timeStr);
}

From source file:fr.inria.ucn.Helpers.java

/**
 * Collectors and Listeners should use this method to send the results to the service.
 * @param c/*  w  w w  . j  av  a2  s.c om*/
 * @param cid data collection id (maps to mongodb collection used to store the data)
 * @param ts  periodic collection timestamp or event time if triggered by timestamp
 * @param data 
 */
@SuppressLint("SimpleDateFormat")
public static void sendResultObj(Context c, String cid, long ts, JSONObject data) {
    try {

        // wrap the collected data object to a common object format
        JSONObject res = new JSONObject();

        // data collection in the backend db
        res.put("collection", cid);

        // store unique user id to each result object
        res.put("uid", getDeviceUuid(c));

        // app version to help to detect data format changes
        try {
            PackageManager manager = c.getPackageManager();
            PackageInfo info = manager.getPackageInfo(c.getPackageName(), 0);
            res.put("app_version_name", info.versionName);
            res.put("app_version_code", info.versionCode);
        } catch (NameNotFoundException e) {
        }

        // event and current time in UTC JSON date format
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S'Z'");
        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
        res.put("ts_event", sdf.format(new Date(ts)));
        res.put("ts", sdf.format(new Date()));
        res.put("tz", TimeZone.getDefault().getID()); // devices current timezone
        res.put("tz_offset", TimeZone.getDefault().getOffset(ts)); // ts offset to this event

        // the data obj
        res.put("data", data);

        // ask the service to handle the data
        Intent intent = new Intent(c, CollectorService.class);
        intent.setAction(Constants.ACTION_DATA);
        intent.putExtra(Constants.INTENT_EXTRA_DATA, res.toString());
        c.startService(intent);

        Log.d(Constants.LOGTAG, res.toString(4));

    } catch (JSONException ex) {
        Log.w(Constants.LOGTAG, "failed to create json obj", ex);
    }
}

From source file:ac.elements.parser.ExtendedFunctions.java

/**
 * Formats a number given as the number of milliseconds String or Long and
 * converts it to a format "H'h' m'm' s's'". Periods longer then a day do
 * not work in this method. If conversion doesn't work it returns the Object
 * casted as a string. (SimpleDateFormat syntax).
 * //w  w w .j av  a2s . co m
 * @returns null if myObject is null, otherwise a formatted time period as a
 *          string.
 * @see java.text.SimpleDateFormat
 */
public static String timePeriod(Object myObject) {

    long timePeriodInMilliseceonds = 0;

    if (myObject == null)
        return null;

    try {

        if (myObject instanceof String) {
            timePeriodInMilliseceonds = Long.parseLong(myObject.toString());
        } else if (myObject instanceof Number) {
            timePeriodInMilliseceonds = ((Number) myObject).longValue();
        } else {
            return "Not supported: ".concat(myObject.getClass().getName());
        }

        String format = "D' days' H'h' mm'm' ss's'";
        if (timePeriodInMilliseceonds < 60 * 1000l)
            format = "ss's'";
        else if (timePeriodInMilliseceonds < 3600 * 1000l)
            format = "mm'm' ss's'";
        else if (timePeriodInMilliseceonds < 3600 * 24 * 1000l)
            format = "H'h' mm'm' ss's'";
        else if (timePeriodInMilliseceonds < 3600 * 48 * 1000l) {
            format = "D' day' H'h' mm'm' ss's'";
        }

        // Get Greenwich time zone.
        TimeZone theTz = TimeZone.getTimeZone("GMT");

        SimpleDateFormat mySimpleDateFormat = new SimpleDateFormat(format);
        mySimpleDateFormat.setTimeZone(theTz);

        // create a date in the locale's calendar,
        // set its timezone and hour.
        Calendar day = Calendar.getInstance();
        day.setTimeZone(theTz);
        day.setTime(new Date(timePeriodInMilliseceonds));
        day.roll(Calendar.DAY_OF_MONTH, false);
        day.set(Calendar.HOUR, day.get(Calendar.HOUR));

        return mySimpleDateFormat.format(day.getTime());

    } catch (NullPointerException npe) {
        // npe.printStackTrace();
        return null;
    } catch (NumberFormatException nfe) {
        // nfe.printStackTrace();
        return null;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }

}

From source file:ac.elements.io.Signature.java

/**
 * The time stamp used in the AWS request. It must be in a specific format
 * (eg. 2007-01-31T23:59:59Z)//from w  w w .  ja va 2 s.c o  m
 * 
 * <p>
 * It must be a date time object, with the complete date plus hours,
 * minutes, and seconds, for more information, go to
 * {@link "http://www.w3.org/TR/xmlschema-2/#dateTime"}).
 * 
 * <p>
 * For example: 2007-01-31T23:59:59Z. Although it is not required, we
 * recommend you provide the time stamp in the Coordinated Universal Time
 * (Greenwich Mean Time) time zone.
 * 
 * <p>
 * The request automatically expires 15 minutes after the time stamp (in
 * other words, AWS does not process a request if the request time stamp is
 * more than 15 minutes earlier than the current time on AWS servers). Make
 * sure your server's time is set correctly.
 * 
 * @return the correctly formatted time stamp
 */
private static String getTimeStamp() {
    final String dateFormat = "yyyy-MM-dd\'T\'HH:mm:ss\'Z\'";
    final SimpleDateFormat format = new SimpleDateFormat(dateFormat, Locale.US);
    format.setTimeZone(TimeZone.getTimeZone("UTC"));
    return format.format(new Date());
}

From source file:dbs_project.util.Utils.java

public static InsertRowsStatement getInsertStatement(String tableName, List<SimpleColumn> columns,
        int rowCount) {
    List<String> columnNames = new ArrayList<>();
    List<List<String>> data = new ArrayList<>();
    java.sql.Date tmp = new java.sql.Date(0);

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    format.setTimeZone(TimeZone.getTimeZone("UTC"));

    for (SimpleColumn col : columns) {
        columnNames.add(col.getName());//from   w ww .j  av a  2s. c o  m
    }
    for (int i = 0; i < rowCount; ++i) {
        List<String> rowData = new ArrayList<>();

        for (SimpleColumn col : columns) {
            if (col.getType() == Type.DATE) {
                /*tmp.setTime(col.getDate(i).getTime());
                rowData.add(tmp.toString());*/
                rowData.add(format.format(col.getDate(i)));
            } else {
                rowData.add(col.getString(i));
            }
        }
        data.add(rowData);
    }
    return new InsertRowsStatementImpl(data, tableName, columnNames);
}

From source file:com.funambol.exchange.util.DateTools.java

public static String addOneDay(String date) throws ParseException {
    SimpleDateFormat formatter = new SimpleDateFormat(DATE_FORMAT_WEBDAV);
    String retval;//from  w w  w.ja v  a2 s . co  m

    formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
    Date dt = formatter.parse(date);
    retval = formatter.format(new Date(dt.getTime() + 24 * 60 * 60 * 1000));
    return retval;
}

From source file:com.funambol.exchange.util.DateTools.java

public static String subtractOneDay(String date) throws ParseException {
    SimpleDateFormat formatter = new SimpleDateFormat(DATE_FORMAT_WEBDAV);
    String retval;/*ww  w  .  java2  s .c  om*/

    formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
    Date dt = formatter.parse(date);
    retval = formatter.format(new Date(dt.getTime() - 24 * 60 * 60 * 1000));
    return retval;
}

From source file:com.krawler.spring.authHandler.authHandler.java

public static DateFormat getPrefDateFormatter(String userTimeFormatId, String timeZoneDiff, String pref)
        throws ServiceException {
    SimpleDateFormat sdf = null;
    try {//from   w ww.  j  ava 2  s . com
        String dateformat = "";
        if (userTimeFormatId.equals("1")) {
            dateformat = pref.replace('H', 'h');
            if (!dateformat.equals(pref)) {
                dateformat += " a";
            }
        } else {
            dateformat = pref;
        }
        sdf = new SimpleDateFormat(dateformat);
        sdf.setTimeZone(TimeZone.getTimeZone("GMT" + timeZoneDiff));
    } catch (Exception e) {
        throw ServiceException.FAILURE("authHandlerDAOImpl.getPrefDateFormatter", e);
    }
    return sdf;
}

From source file:com.krawler.spring.authHandler.authHandler.java

public static DateFormat getUserPrefDateFormatter(String userTimeFormatId, String pref)
        throws ServiceException {
    SimpleDateFormat sdf = null;
    try {//from ww  w .  j  a va 2s .  co  m
        String dateformat = "";
        if (userTimeFormatId.equals("1")) {
            dateformat = pref.replace('H', 'h');
            if (!dateformat.equals(pref)) {
                dateformat += " a";
            }
        } else {
            dateformat = pref;
        }
        sdf = new SimpleDateFormat(dateformat);
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+00:00"));
    } catch (Exception e) {
        throw ServiceException.FAILURE("authHandlerDAOImpl.getUserPrefDateFormatter", e);
    }
    return sdf;
}

From source file:org.opendatakit.common.utils.WebUtils.java

/**
 * Return the ISO8601 string representation of a date.
 *
 * @param d/* w  ww .  jav a  2 s  .com*/
 * @return
 */
public static final String iso8601Date(Date d) {
    if (d == null)
        return null;
    // SDF is not thread-safe
    SimpleDateFormat asGMTiso8601 = new SimpleDateFormat(PATTERN_ISO8601); // with
                                                                           // time
                                                                           // zone
    asGMTiso8601.setTimeZone(TimeZone.getTimeZone("GMT"));
    return asGMTiso8601.format(d);
}