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:info.archinnov.achilles.it.TestInterceptorsSimpleEntity.java

@Test
public void should_trigger_for_dsl_iterator() throws Exception {
    //Given//  w  w w .  j a  va 2s .  c om
    final Map<String, Object> values = new HashMap<>();
    final long id = RandomUtils.nextLong(0L, Long.MAX_VALUE);
    values.put("id", id);
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
    dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
    final Date date1 = dateFormat.parse("2015-10-01 00:00:00 GMT");
    final Date date9 = dateFormat.parse("2015-10-09 00:00:00 GMT");
    values.put("date1", "'2015-10-01 00:00:00+0000'");
    values.put("date2", "'2015-10-02 00:00:00+0000'");
    values.put("date3", "'2015-10-03 00:00:00+0000'");
    values.put("date4", "'2015-10-04 00:00:00+0000'");
    values.put("date5", "'2015-10-05 00:00:00+0000'");
    values.put("date6", "'2015-10-06 00:00:00+0000'");
    values.put("date7", "'2015-10-07 00:00:00+0000'");
    values.put("date8", "'2015-10-08 00:00:00+0000'");
    values.put("date9", "'2015-10-09 00:00:00+0000'");
    scriptExecutor.executeScriptTemplate("SimpleEntity/insert_many_rows.cql", values);

    //When
    final Iterator<SimpleEntity> actuals = manager.dsl().select().consistencyList().simpleSet().simpleMap()
            .value().simpleMap().fromBaseTable().where().id_Eq(id).date_Gte_And_Lt(date1, date9).iterator();

    //Then
    assertThat(actuals.next().getValue()).isEqualTo("postLoad_id - date1");
    assertThat(actuals.next().getValue()).isEqualTo("postLoad_id - date2");
    assertThat(actuals.next().getValue()).isEqualTo("postLoad_id - date3");
    assertThat(actuals.next().getValue()).isEqualTo("postLoad_id - date4");
    assertThat(actuals.next().getValue()).isEqualTo("postLoad_id - date5");
    assertThat(actuals.next().getValue()).isEqualTo("postLoad_id - date6");
    assertThat(actuals.next().getValue()).isEqualTo("postLoad_id - date7");
    assertThat(actuals.next().getValue()).isEqualTo("postLoad_id - date8");
    assertThat(actuals.hasNext()).isFalse();
}

From source file:nz.net.orcon.kanban.tools.ListTools.java

private SimpleDateFormat createSimpleDateFormat() {
    // xs:dateTime('2008-01-01T00:00:00.000+02:00')
    // yyyy-MM-dd'T'HH:mm:ss.SSSXXX
    final SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    df.setTimeZone(TimeZone.getTimeZone("UTC"));
    df.applyLocalizedPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");
    return df;/*from   w w w .  j a v a  2  s . c o  m*/
}

From source file:com.opentransport.rdfmapper.nmbs.NetworkDisturbanceFetcher.java

private void scrapeNetworkDisturbanceWebsite(String language, String _url) {
    Document doc;//from   ww  w .j  a  v  a 2  s.com
    int i = 0;
    //English Version
    try {
        URL url = new URL(_url);
        HttpURLConnection request = (HttpURLConnection) url.openConnection();
        request.connect();

        // Convert to a JSON object to print data
        JsonParser jp = new JsonParser(); //from gson
        JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //Convert the input stream to a json element
        JsonArray disturbances = root.getAsJsonObject().getAsJsonArray("him");

        for (JsonElement el : disturbances) {
            JsonObject obj = (JsonObject) el;

            String header = obj.get("header").getAsString();
            String description = obj.get("text").getAsString();
            String urls = ""; // todo check JsonNull

            String begin = obj.get("begin").getAsString(); // dd.MM.yyyy HH:mm
            String end = obj.get("end").getAsString(); // dd.MM.yyyy HH:mm
            SimpleDateFormat df = new SimpleDateFormat("dd.MM.yy HH:mm");
            df.setTimeZone(TimeZone.getTimeZone("Europe/Brussels"));

            Date date;
            long startEpoch, endEpoch;
            try {
                date = df.parse(begin);
                startEpoch = date.getTime() / 1000;
                date = df.parse(end);
                endEpoch = date.getTime() / 1000;
            } catch (ParseException ex) {
                // When time range is missing, take 12 hours before and after
                startEpoch = new Date().getTime() - 43200;
                endEpoch = new Date().getTime() + 43200;

                Logger.getLogger(NetworkDisturbanceFetcher.class.getName()).log(Level.SEVERE, null, ex);
            }

            int startStationId, endStationId, impactStationId;
            if (obj.has("startstation_extId")) {
                startStationId = obj.get("startstation_extId").getAsInt();
            } else {
                startStationId = -1;
            }
            if (obj.has("endstation_extId")) {
                endStationId = obj.get("endstation_extId").getAsInt();
            } else {
                endStationId = -1;
            }
            if (obj.has("impactstation_extId")) {
                impactStationId = obj.get("impactstation_extId").getAsInt();
            } else {
                impactStationId = -1;
            }

            String id = obj.get("id").getAsString();

            NetworkDisturbance disturbance = new NetworkDisturbance(header, description, urls, language,
                    startEpoch, endEpoch, startStationId, endStationId, impactStationId, id);

            networkDisturbances.add(disturbance);
        }

    } catch (IOException ex) {
        Logger.getLogger(NetworkDisturbanceFetcher.class.getName()).log(Level.SEVERE, null, ex);
        errorWriter.writeError(ex.toString());
    }

}

From source file:com.hypersocket.server.handlers.impl.ContentHandlerImpl.java

/**
 * Sets the Date and Cache headers for the HTTP Response
 *
 * @param response/*from  www.j  a v  a2s  .  c  o m*/
 *            HTTP response
 * @param fileToCache
 *            file to extract content type
 */
private void setDateAndCacheHeaders(HttpServletResponse response, String path) {
    SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
    dateFormatter.setTimeZone(TimeZone.getTimeZone(HTTP_DATE_GMT_TIMEZONE));

    // Date header
    Calendar time = new GregorianCalendar();
    response.setHeader(HttpHeaders.DATE, dateFormatter.format(time.getTime()));

    // Add cache headers
    time.add(Calendar.SECOND, HTTP_CACHE_SECONDS);
    response.setHeader(HttpHeaders.EXPIRES, dateFormatter.format(time.getTime()));
    response.setHeader(HttpHeaders.CACHE_CONTROL, "private, max-age=" + HTTP_CACHE_SECONDS);
    try {
        response.setHeader(HttpHeaders.LAST_MODIFIED, dateFormatter.format(new Date(getLastModified(path))));
    } catch (FileNotFoundException e) {
    }
}

From source file:com.arantius.tivocommander.Person.java

private void requestFinished() {
    if (--mOutstandingRequests > 0) {
        return;// w ww  .j  av  a 2s. com
    }
    setProgressBarIndeterminateVisibility(false);

    if (mPerson == null || mCredits == null) {
        setContentView(R.layout.no_results);
        return;
    }

    setContentView(R.layout.list_person);

    // Credits.
    JsonNode[] credits = new JsonNode[mCredits.size()];
    int i = 0;
    for (JsonNode credit : mCredits) {
        credits[i++] = credit;
    }

    ListView lv = getListView();
    CreditsAdapter adapter = new CreditsAdapter(Person.this, R.layout.item_person_credits, credits);
    lv.setAdapter(adapter);
    lv.setOnItemClickListener(mOnItemClickListener);

    // Name.
    ((TextView) findViewById(R.id.person_name)).setText(mName);

    // Role.
    JsonNode rolesNode = mPerson.path("roleForPersonId");
    String[] roles = new String[rolesNode.size()];
    for (i = 0; i < rolesNode.size(); i++) {
        roles[i] = rolesNode.path(i).asText();
        roles[i] = Utils.ucFirst(roles[i]);
    }
    ((TextView) findViewById(R.id.person_role)).setText(Utils.join(", ", roles));

    // Birth date.
    TextView birthdateView = ((TextView) findViewById(R.id.person_birthdate));
    if (mPerson.has("birthDate")) {
        Date birthdate = Utils.parseDateStr(mPerson.path("birthDate").asText());
        SimpleDateFormat dateFormatter = new SimpleDateFormat("MMMMM d, yyyy", Locale.US);
        dateFormatter.setTimeZone(TimeZone.getDefault());
        Spannable birthdateStr = new SpannableString("Birthdate: " + dateFormatter.format(birthdate));
        birthdateStr.setSpan(new ForegroundColorSpan(Color.WHITE), 11, birthdateStr.length(), 0);
        birthdateView.setText(birthdateStr);
    } else {
        birthdateView.setVisibility(View.GONE);
    }

    // Birth place.
    TextView birthplaceView = ((TextView) findViewById(R.id.person_birthplace));
    if (mPerson.has("birthPlace")) {
        Spannable birthplaceStr = new SpannableString("Birthplace: " + mPerson.path("birthPlace").asText());
        birthplaceStr.setSpan(new ForegroundColorSpan(Color.WHITE), 12, birthplaceStr.length(), 0);
        birthplaceView.setText(birthplaceStr);
    } else {
        birthplaceView.setVisibility(View.GONE);
    }

    ImageView iv = (ImageView) findViewById(R.id.person_image);
    View pv = findViewById(R.id.person_image_progress);
    String imgUrl = Utils.findImageUrl(mPerson);
    new DownloadImageTask(this, iv, pv).execute(imgUrl);
}

From source file:com.gae.ImageUpServlet.java

public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    //DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
    //ReturnValue value = new ReturnValue();
    MemoryFileItemFactory factory = new MemoryFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    resp.setContentType("image/jpeg");
    ServletOutputStream out = resp.getOutputStream();
    try {//from  w w  w .  j  a  v  a 2  s .  c  o m
        List<FileItem> list = upload.parseRequest(req);
        //FileItem list = upload.parseRequest(req);
        for (FileItem item : list) {
            if (!(item.isFormField())) {
                filename = item.getName();
                if (filename != null && !"".equals(filename)) {
                    int size = (int) item.getSize();
                    byte[] data = new byte[size];
                    InputStream in = item.getInputStream();
                    in.read(data);
                    ImagesService imagesService = ImagesServiceFactory.getImagesService();
                    Image newImage = ImagesServiceFactory.makeImage(data);
                    byte[] newImageData = newImage.getImageData();

                    //imgkey = KeyFactory.createKey(Imagedat.class.getSimpleName(), filename.split(".")[0]);   
                    //imgkey = KeyFactory.createKey(Imagedat.class.getSimpleName(), filename.split(".")[0]);   

                    out.write(newImageData);
                    out.flush();

                    DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
                    Key key = KeyFactory.createKey(kind, skey);
                    Blob blobImage = new Blob(newImageData);
                    DirectBeans_textjson dbeans = new DirectBeans_textjson();
                    /*  ?Date?     */
                    //Entity entity = dbeans.setentity("add", kind, true, key, id, val);

                    //ReturnValue value = dbeans.Called.setentity("add", kind, true, key, id, val);
                    //Entity entity = value.entity;
                    //DirectBeans.ReturnValue value = new DirectBeans.ReturnValue();
                    DirectBeans_textjson.entityVal eval = dbeans.setentity("add", kind, true, key, id, val);
                    Entity entity = eval.entity;

                    /*  ?Date                         */
                    //for(int i=0; i<id.length; i++ ){
                    //   if(id[i].equals("image")){
                    //      //filetitle = val[i];
                    //      //imgkey = KeyFactory.createKey(Imagedat.class.getSimpleName(), val[i]);   
                    //   }
                    //}                

                    entity.setProperty("image", blobImage);
                    Date date = new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd:HHmmss");
                    sdf.setTimeZone(TimeZone.getTimeZone("JST"));
                    entity.setProperty("moddate", sdf.format(date));
                    //DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
                    ds.put(entity);
                    out.println("? KEY:" + key);
                }
            }
        }
    } catch (FileUploadException e) {
        e.printStackTrace();
    } finally {
        if (out != null) {
            out.close();
        }
    }
}

From source file:com.tinyhydra.botd.sql.SQLInterface.java

public long GetDate() {
    System.out.println("Returning today's date in GMT-8");
    SimpleDateFormat date_format_gmt = new SimpleDateFormat("yyyy-MM-dd");
    date_format_gmt.setTimeZone(TimeZone.getTimeZone("GMT-8"));
    long returnDate = 0;
    try {/*  w w w.  j a v  a 2 s . co  m*/
        returnDate = date_format_gmt.parse(date_format_gmt.format(Calendar.getInstance().getTime())).getTime();
    } catch (ParseException pex) {
        pex.printStackTrace();
    }
    return returnDate;
}

From source file:com.robin.utilities.Utilities.java

/**
 * Formats a date to string by SimpledateFormat rules in a given time zone.
 * @param date the date to write to string
 * @param dateFormat the format string of the returned time text. (e.g.
 *            "yyyy-MM-dd HH:mm:ss")/*  w  ww  . jav  a2  s  . c om*/
 * @param timeZone the time zone of the current time
 * @return The date formatted according to the given dateFormat and time
 *         zone.
 */
public String dateToString(final Date date, final String dateFormat, final TimeZone timeZone) {
    SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
    sdf.setTimeZone(timeZone);
    return sdf.format(date);
}

From source file:org.onebusaway.webapp.actions.where.ScheduleAction.java

private <T> List<T2<String, List<T>>> getTimesByFormatKey(List<T> stopTimes, String format,
        IAdapter<T, Date> adapter) {

    SimpleDateFormat df = new SimpleDateFormat(format);
    df.setTimeZone(_timeZone);

    List<T2<String, List<T>>> tuples = new ArrayList<T2<String, List<T>>>();
    T2<String, List<T>> tuple = null;

    for (T bean : stopTimes) {
        Date date = adapter.adapt(bean);
        String key = df.format(date);
        if (tuple == null || !tuple.getFirst().equals(key)) {
            if (tuple != null && !tuple.getSecond().isEmpty())
                tuples.add(tuple);/*from  ww w.  ja  v  a  2  s .c  o m*/
            List<T> beans = new ArrayList<T>();
            tuple = Tuples.tuple(key, beans);
        }
        tuple.getSecond().add(bean);
    }

    if (tuple != null && !tuple.getSecond().isEmpty())
        tuples.add(tuple);

    return tuples;
}

From source file:com.shampan.db.services.StatusServiceTest.java

public void unixToHuman() throws ParseException {
    //        long unixSeconds = 1447681923;
    long unixSeconds = System.currentTimeMillis();
    //        Date date = new Date(unixSeconds*1000L); // *1000 is to convert seconds to milliseconds
    Date date = new Date(unixSeconds); // *1000 is to convert seconds to milliseconds
    //        System.out.println(date);
    //        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z"); // the format of your date
    //        sdf.setTimeZone(TimeZone.getTimeZone("GMT+14")); // give a timezone reference for formating (see comment at the bottom
    //        String formattedDate = sdf.format(date);
    //        System.out.println("GMT other country  Date = " + formattedDate);
    //        long a = sdf.parse(formattedDate).getTime();
    //        System.out.println("unixGMTTime = " + a);
    SimpleDateFormat sdfForBD = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z"); // the format of your date
    sdfForBD.setTimeZone(TimeZone.getTimeZone("GMT+6")); // give a timezone reference for formating (see comment at the bottom
    String formattedDateForBD = sdfForBD.format(date);
    System.out.println("BD Date = " + formattedDateForBD);
    //        long bdTime = sdfForBD.parse(formattedDateForBD).getTime();
    //        System.out.println("unixGMTTime = " + bdTime);
    SimpleDateFormat sdfForGMT0 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z"); // the format of your date
    sdfForGMT0.setTimeZone(TimeZone.getTimeZone("GMT+0")); // give a timezone reference for formating (see comment at the bottom
    String formattedDateForGMT0 = sdfForGMT0.format(date);
    System.out.println("BD Date = " + formattedDateForGMT0);
    long gmt0Time1 = sdfForBD.parse(formattedDateForGMT0).getTime();
    long gmt0Time2 = sdfForBD.parse(formattedDateForBD).getTime();
    System.out.println(gmt0Time1);
    System.out.println(gmt0Time2);
    //        System.out.println("unixTime = " + bT);

}