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.TestEntityWithComplexTypes.java

private Date buildDate() throws ParseException {

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
    dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
    return dateFormat.parse("2015-10-01 00:00:00 GMT");
}

From source file:com.room5.server.spring_boot.jmx.JMXServerStatistics.java

@ManagedMetric(description = "Current interval start time.", displayName = "Current interval start time.", metricType = MetricType.COUNTER, currencyTimeLimit = 120)
public String getIntervalStart() {
    long start = intervalClock.getIntervalStartMillis(intervalClock.getCurrentInterval());

    //format /*from  w  ww  .j av a  2 s. c  om*/
    SimpleDateFormat df = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss z");
    df.setTimeZone(TimeZone.getTimeZone("UTC"));

    return df.format(new Date(start));
}

From source file:com.hackensack.umc.activity.ViewProfileActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_view_profile);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    sharedPreferences = getSharedPreferences(Constant.SHAREPREF_TAG, MODE_PRIVATE);
    insuranceInfoTv = (TextView) findViewById(R.id.prof_insurance_tv);
    if (Util.isUserLogin(this) && Util.isPatientIdValid(this)) {

        try {/*ww w .  j av  a2 s .  c  o m*/
            mPatient = new LoginUserData(new JSONObject(Util.getPatientJSON(this)));
            ((TextView) findViewById(R.id.profile_fname)).setText(mPatient.getFirstName());
            ((TextView) findViewById(R.id.prof_lname)).setText(mPatient.getLastName());
            ((TextView) findViewById(R.id.prof_license)).setText(
                    TextUtils.isEmpty(mPatient.getDrivingLicense()) ? "-" : mPatient.getDrivingLicense());
            DateFormat formatterDate = new SimpleDateFormat("MM-dd-yyyy");

            Date d = null;
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
                d = sdf.parse(mPatient.getBirthDate());
            } catch (Exception e) {
                Log.e("Date", " " + e);
            }

            //Bug is there : Null Pointer : Appointment Date
            ((TextView) findViewById(R.id.prof_date)).setText(formatterDate.format(d.getTime()));
            ((TextView) findViewById(R.id.prof_gender_tv)).setText(mPatient.getGender());
            //Code for getting and displaying phone numbers
            ArrayList<Telecom> telecom = mPatient.getTelephone();
            Log.v("Telecom", telecom.toString());
            String phonestr = null;
            for (int i = 0; i < telecom.size(); i++) {
                if (((Telecom) telecom.get(i)).getSystem().equalsIgnoreCase(Telecom.TELECOM_EMAIL)) {
                    ((TextView) findViewById(R.id.prof_email)).setText(((Telecom) telecom.get(i)).getValue());
                } else if (((Telecom) telecom.get(i)).getSystem().equalsIgnoreCase(Telecom.TELECOM_PHONE)) {
                    phonestr = telecom.get(i).getValue();
                    final Editable doctorPhoneNum = new SpannableStringBuilder(phonestr);
                    PhoneNumberUtils.formatNumber(doctorPhoneNum,
                            PhoneNumberUtils.getFormatTypeForLocale(Locale.US));
                    if (((Telecom) telecom.get(i)).getUse().equalsIgnoreCase(Telecom.TELECOM_MOBILE_PHONE)) {
                        findViewById(R.id.mobile_ll).setVisibility(View.VISIBLE);
                        ((TextView) findViewById(R.id.prof_mob_num)).setText(doctorPhoneNum);

                    } else if (((Telecom) telecom.get(i)).getUse()
                            .equalsIgnoreCase(Telecom.TELECOM_HOME_PHONE)) {
                        findViewById(R.id.home_ll).setVisibility(View.VISIBLE);
                        ((TextView) findViewById(R.id.prof_home_num)).setText(doctorPhoneNum);

                    } else if (((Telecom) telecom.get(i)).getUse()
                            .equalsIgnoreCase(Telecom.TELECOM_WORK_PHONE)) {
                        findViewById(R.id.work_ll).setVisibility(View.VISIBLE);
                        ((TextView) findViewById(R.id.prof_work_num)).setText(doctorPhoneNum);
                    }
                }
            }
            //Code to get and display address
            if (mPatient.getAddress() != null && mPatient.getAddress().size() > 0) {
                Address address = ((ArrayList<Address>) mPatient.getAddress()).get(0);
                ((TextView) findViewById(R.id.prof_addr_tv)).setText(address.getStreet1() + ","
                        + (TextUtils.isEmpty(address.getStreet2()) ? "" : address.getStreet2() + ",")
                        + address.getCity() + "," + address.getState() + "," + address.getZip() + ","
                        + address.getCountry());
            }

        } catch (Exception e) {
            Log.e("isUserLogin", "", e);

        }
        //Code to get and display insurance info

        new GetInsuranceInfo().execute(mPatient.getMRNId());
    }

    /* mProgressDialog = new ProgressDialog(this);
     mProgressDialog.setCancelable(false);*/
}

From source file:org.opencastproject.remotetest.server.PreProcessingWorkflowTest.java

/**
 * Adds a new recording event to the scheduling service and returns the event id.
 * //from  w w  w .j  av  a 2 s .c om
 * @param start
 *          start date
 * @param end
 *          end date
 * @return the event identifier
 */
private String scheduleEvent(Date start, Date end) throws Exception {
    HttpPost request = new HttpPost(BASE_URL + "/recordings");

    // Create the request body
    SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
    f.setTimeZone(TimeZone.getTimeZone("UTC"));

    String dublinCoreXml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>"
            + "<dublincore xmlns=\"http://www.opencastproject.org/xsd/1.0/dublincore/\" xmlns:dcterms=\"http://purl.org/dc/terms/\" "
            + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><dcterms:creator>demo creator</dcterms:creator>"
            + "<dcterms:contributor>demo contributor</dcterms:contributor>"
            + "<dcterms:temporal xsi:type=\"dcterms:Period\">start={startTime}; end={endTime}; scheme=W3C-DTF;</dcterms:temporal>"
            + "<dcterms:language>en</dcterms:language><dcterms:spatial>{device}</dcterms:spatial><dcterms:title>demo title</dcterms:title>"
            + "<dcterms:license>creative commons</dcterms:license></dublincore>";
    dublinCoreXml = dublinCoreXml.replace("{device}", CAPTURE_AGENT_ID).replace("{startTime}", f.format(start))
            .replace("{endTime}", f.format(end));

    String captureAgentMetadata = "event.location=testdevice\norg.opencastproject.workflow.definition="
            + WORKFLOW_DEFINITION_ID + "\n";

    // Prepare the request
    List<NameValuePair> formParams = new ArrayList<NameValuePair>();
    formParams.add(new BasicNameValuePair("dublincore", dublinCoreXml));
    formParams.add(new BasicNameValuePair("agentparameters", captureAgentMetadata));
    request.setEntity(new UrlEncodedFormEntity(formParams, "UTF-8"));

    // Submit and check the response
    HttpResponse response = client.execute(request);
    assertEquals(HttpStatus.SC_CREATED, response.getStatusLine().getStatusCode());
    String responseHeader = StringUtils.trimToNull(response.getFirstHeader("Location").getValue());
    assertNotNull(responseHeader);
    Pattern p = Pattern.compile(".*?(\\d+)\\.xml");
    Matcher m = p.matcher(responseHeader);
    String eventId = null;
    if (m.find()) {
        eventId = m.group(1);
        assertNotNull("No event id found", eventId);
    } else {
        fail("Unknown location returned");
    }
    return eventId;
}

From source file:edu.du.penrose.systems.fedoraApp.reports.BatchIngestReport.java

/**
 * Write a report footer, containing a count of completed and failed, to the open report log.
 * //from w  ww . j a v  a2 s  .c o m
 * @throws FatalException
 */
public void finishReport() throws FatalException {

    SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
    dateFormat.setTimeZone(TimeZone.getTimeZone("MST"));

    SimpleDateFormat dateFormat2 = new SimpleDateFormat("HH:mm:ss");
    dateFormat2.setTimeZone(TimeZone.getTimeZone("UTC"));

    String header = "* Results -";
    String num_completed_msg = "\tDocuments Completed \t= " + this.documentsCompletedCount;
    String num_failed_msg = "\tDocuments FAILED \t= " + this.documentsFailedCount;
    String num_warnings_msg = "\tWarnings \t\t= " + this.warningsCount;

    this.endTime = System.currentTimeMillis();
    long fedoraIngestTime = this.endTime - this.startFedoraIngestTime;
    long totalIngestTime = this.endTime - this.startTime;

    String footer = "End of Batch Ingest Report:   " + TimeDateUtils.getCurrentTimeMonthDayYearHourMinute()
            + " Total Time:" + dateFormat2.format(new Date(totalIngestTime)) + "    Fedora Ingest Time: "
            + dateFormat2.format(new Date(fedoraIngestTime)) + " *********";

    this.logger.info("\n" + header);
    this.logger.info("\n" + num_completed_msg);
    this.logger.info("\n" + num_warnings_msg);
    this.logger.info("\n" + num_failed_msg);

    try {
        this.myReport.newLine();
        this.writeToReport(header);

        this.myReport.newLine();
        this.writeToReport(num_completed_msg);
        this.myReport.newLine();
        this.writeToReport(num_warnings_msg);
        this.myReport.newLine();
        this.writeToReport(num_failed_msg);

        this.myReport.newLine();
        this.outputWarningReport();

        this.myReport.newLine();
        this.outputFailedReport();

        this.logger.info("\n\n" + footer + "\n\n");
        this.myReport.newLine();
        this.myReport.newLine();
        this.writeToReport(footer);
        this.myReport.newLine();
        this.myReport.newLine();

        this.myReport.close();
    } catch (IOException e) {
        this.logger.warn("Unable to write to report:" + e);
        // throw new FatalException( "Unable to write to report:"+e );
    }
}

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

public String getFormattedDate(String format, Date date) {
    SimpleDateFormat df = new SimpleDateFormat(format);
    df.setTimeZone(_timeZone);
    return df.format(date);
}

From source file:com.dubture.jenkins.digitalocean.ComputerLauncher.java

private String getUtcDate(Date date) {
    SimpleDateFormat utcFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
    utcFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    return utcFormat.format(date);
}

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

/**
 * Sets the Date header for the HTTP response
 *
 * @param response/*from ww  w.ja  v  a 2s . com*/
 *            HTTP response
 */
private void setDateHeader(HttpServletResponse response) {
    SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
    dateFormatter.setTimeZone(TimeZone.getTimeZone(HTTP_DATE_GMT_TIMEZONE));

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

From source file:fr.gael.dhus.service.job.SendLogsJob.java

@Override
protected void executeInternal(JobExecutionContext arg0) throws JobExecutionException {
    if (!configurationManager.getSendLogsCronConfiguration().isActive())
        return;/*from w  ww  .  j a v  a2s.  c  om*/
    long start = System.currentTimeMillis();
    logger.info("SCHEDULER : Send Administrative logs.");
    if (!DHuS.isStarted()) {
        logger.warn("SCHEDULER : Not run while system not fully initialized.");
        return;
    }

    String[] addresses = configurationManager.getSendLogsCronConfiguration().getAddresses().split(",");
    // Case of no addresses available: use system support
    if ((addresses == null) || (addresses.length == 0) || "".equals(addresses[0].trim())) {
        String email = configurationManager.getSupportConfiguration().getMail();
        if ((email == null) || "".equals(email)) {
            throw new MailException("Support e-mail not configured, " + "system logs will not be send");
        }
        addresses = new String[] { email };
    }

    RollingFileAppender rollingFileAppender = (RollingFileAppender) ((org.apache.logging.log4j.core.Logger) LogManager
            .getRootLogger()).getAppenders().get("RollingFile");
    if (rollingFileAppender == null) {
        throw new MailException("No rolling log file defined");
    }

    String logPath = rollingFileAppender.getFileName();

    if ((logPath == null) || logPath.trim().equals("")) {
        throw new MailException("Log file not defined");
    }

    File logs = new File(logPath);
    if (!logs.exists()) {
        throw new MailException("Log file not present : " + logs.getPath());
    }

    Date now = new Date();
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'@'HH:mm:ss");
    df.setTimeZone(TimeZone.getTimeZone("GMT"));
    String docFilename = configurationManager.getNameConfiguration().getShortName().toLowerCase() + "-"
            + df.format(now);

    File zipLogs;
    try {
        zipLogs = File.createTempFile(docFilename, ".zip");
    } catch (IOException e) {
        throw new MailException("Cannot create temporary zip log file.", e);
    }

    // compress logs file to zip format
    FileOutputStream fos;
    ZipOutputStream zos = null;
    FileInputStream fis = null;
    try {
        int length;
        byte[] buffer = new byte[1024];
        ZipEntry entry = new ZipEntry(docFilename + ".txt");

        fos = new FileOutputStream(zipLogs);
        zos = new ZipOutputStream(fos);
        fis = new FileInputStream(logs);

        zos.setLevel(Deflater.BEST_COMPRESSION);
        zos.putNextEntry(entry);
        while ((length = fis.read(buffer)) > 0) {
            zos.write(buffer, 0, length);
        }
    } catch (IOException e) {
        throw new MailException("An error occurred during compression " + "logs file, cannot send logs !", e);
    } finally {
        try {
            if (fis != null) {
                fis.close();
            }
            if (zos != null) {
                zos.closeEntry();
                zos.close();
            }
        } catch (IOException e) {
            throw new MailException("An error occurred during compression " + "logs file, cannot send logs !",
                    e);
        }
    }

    EmailAttachment attachment = new EmailAttachment();
    attachment.setDescription(
            configurationManager.getNameConfiguration().getShortName() + " Logs " + now.toString());
    attachment.setPath(zipLogs.getPath());
    attachment.setName(zipLogs.getName());

    // Prepare the addresses
    List<String> ads = new ArrayList<String>();
    for (String email : addresses) {
        StringTokenizer tk = new StringTokenizer(email, ", ");
        while (tk.hasMoreTokens()) {
            String token = tk.nextToken().trim();
            if (!token.isEmpty())
                ads.add(token);
        }
    }
    for (String email : ads) {
        try {
            String server = configurationManager.getServerConfiguration().getExternalHostname();
            String url = configurationManager.getServerConfiguration().getExternalUrl();

            mailServer.send(email, null, null,
                    "[" + configurationManager.getNameConfiguration().getShortName().toLowerCase() + "@"
                            + server + "] logs of " + df.format(now),
                    "Here is attached " + configurationManager.getNameConfiguration().getShortName()
                            + " logs of \"" + url + "\" host.\n\n" + "Kind Regards.\nThe "
                            + configurationManager.getNameConfiguration().getShortName() + " Team.",
                    attachment);
            logger.info("Logs Sent to " + email);
        } catch (EmailException e) {
            throw new MailException("Cannot send logs to " + email, e);
        }
    }

    if (!zipLogs.delete()) {
        logger.warn("Cannot remove mail attachment: " + zipLogs.getAbsolutePath());
    }

    logger.info("SCHEDULER : Send Administrative logs done - " + (System.currentTimeMillis() - start) + "ms");
}

From source file:info.archinnov.achilles.it.TestInterceptorsSimpleEntity.java

@Test
public void should_trigger_for_dsl_select() throws Exception {
    //Given//  w ww  . j  a v  a  2  s  . 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 List<SimpleEntity> actuals = manager.dsl().select().consistencyList().simpleSet().simpleMap().value()
            .simpleMap().fromBaseTable().where().id_Eq(id).date_Gte_And_Lt(date1, date9).getList();

    //Then
    assertThat(actuals).hasSize(8);
    assertThat(actuals.get(0).getValue()).isEqualTo("postLoad_id - date1");
    assertThat(actuals.get(1).getValue()).isEqualTo("postLoad_id - date2");
    assertThat(actuals.get(2).getValue()).isEqualTo("postLoad_id - date3");
    assertThat(actuals.get(3).getValue()).isEqualTo("postLoad_id - date4");
    assertThat(actuals.get(4).getValue()).isEqualTo("postLoad_id - date5");
    assertThat(actuals.get(5).getValue()).isEqualTo("postLoad_id - date6");
    assertThat(actuals.get(6).getValue()).isEqualTo("postLoad_id - date7");
    assertThat(actuals.get(7).getValue()).isEqualTo("postLoad_id - date8");
}