Example usage for java.text DateFormat setTimeZone

List of usage examples for java.text DateFormat setTimeZone

Introduction

In this page you can find the example usage for java.text DateFormat 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.example.todd.mrqsample.MainActivity.java

@Override // from MrqDataProvider
public MrqUserContext currentUserContext() {
    DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'");
    dateFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
    try {//ww w .  jav  a 2  s  .  c o m
        Map properties = new HashMap<>();
        List events = new ArrayList<>();
        Map tags = new HashMap<>();

        //Add a flight
        Map fp = new HashMap<>();
        //Add special flight properties (see documentation for MrqEvent)
        fp.put("airline", "UA");
        fp.put("flightNumber", "712");
        fp.put("originAirport", "LAX");
        fp.put("destinationAirport", "ORD");
        fp.put("checkedIn", "false");
        //Add any additional custom Flight properties
        fp.put("travelerLastName", "Doe");
        fp.put("bookingNumber", "1234");
        MrqEvent flight = new MrqEvent(MrqEventType.FLIGHT, dateFormatter.parse("2015-07-13T13:00Z"),
                dateFormatter.parse("2015-07-14T02:40Z"), null, null, fp);
        events.add(flight);

        //Add custom tags
        tags.put("tags", new HashSet<>(Arrays.asList("android", "sample app", "show lots", "todd", "CAL")));

        //Add any custom Context properties
        properties.put("termsOfServiceAccept", "yes");
        properties.put("Loyalty Level", "gold");
        properties.put("Favorite Color", "blue");

        //mrqsdk.this.dataProvider.currentUserContext();

        if (mapp.getMrqContext() == null) {
            mapp.setMrqContext(new MrqUserContext(properties, tags, events));
        }
        return mapp.getMrqContext();

    } catch (ParseException e) {
        throw new IllegalStateException();
    }
}

From source file:org.codice.ddf.spatial.ogc.csw.catalog.transformer.GmdTransformerTest.java

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

From source file:foam.jellyfish.StarwispBuilder.java

public static String getDateTime() {
    DateFormat df = new SimpleDateFormat("yyyy_MM_dd_hh_mm_ss");
    df.setTimeZone(TimeZone.getTimeZone("GMT"));
    return df.format(new Date());
}

From source file:pt.lsts.neptus.plugins.sunfish.awareness.ArgosLocationProvider.java

@Periodic(millisBetweenUpdates = 120000)
public void updatePositions() {
    if (!enabled)
        return;/*from  www.j  a v  a 2  s  . com*/
    try {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        df.setTimeZone(TimeZone.getTimeZone("GMT"));

        DixService srv = new DixService();
        XmlRequestType request = new XmlRequestType();

        if (askCredentials || argosPassword == null) {
            Pair<String, String> credentials = GuiUtils.askCredentials(ConfigFetch.getSuperParentFrame(),
                    "Enter Argos Credentials", getArgosUsername(), getArgosPassword());
            if (credentials == null) {
                enabled = false;
                return;
            }
            setArgosUsername(credentials.first());
            setArgosPassword(credentials.second());
            try {
                PluginUtils.saveProperties("conf/argosCredentials.props", this);
            } catch (Exception e) {
                e.printStackTrace();
                return;
            }
            askCredentials = false;
        }

        request.setUsername(getArgosUsername());
        request.setPassword(getArgosPassword());
        request.setMostRecentPassages(true);
        request.setPlatformId(platformId);
        request.setNbDaysFromNow(10);

        String xml = srv.getDixServicePort().getXml(request).getReturn();
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(new ByteArrayInputStream(xml.getBytes()));
        NodeList locations = doc.getElementsByTagName("location");
        for (int i = 0; i < locations.getLength(); i++) {
            Node locNode = locations.item(i);
            Node platformNode = locNode.getParentNode().getParentNode();
            Node platfId = platformNode.getFirstChild();
            String id = platfId.getTextContent();
            NodeList childs = locNode.getChildNodes();
            String lat = null, lon = null, date = null, locClass = null;

            for (int j = 0; j < childs.getLength(); j++) {
                Node elem = childs.item(j);
                switch (elem.getNodeName()) {
                case "locationDate":
                    date = elem.getTextContent();
                    break;
                case "latitude":
                    lat = elem.getTextContent();
                    break;
                case "longitude":
                    lon = elem.getTextContent();
                    break;
                case "locationClass":
                    locClass = elem.getTextContent();
                    break;
                default:
                    break;
                }
            }
            AssetPosition pos = new AssetPosition("Argos_" + id, Double.parseDouble(lat),
                    Double.parseDouble(lon));
            pos.setSource(getName());
            pos.setType("Argos Tag");
            pos.putExtra("Loc. Class", locClass);
            pos.setTimestamp(df.parse(date.replaceAll("T", " ").replaceAll("Z", "")).getTime());
            if (sitAwareness != null)
                sitAwareness.addAssetPosition(pos);
        }
    } catch (Exception e) {
        e.printStackTrace();
        NeptusLog.pub().error(e);
        sitAwareness
                .postNotification(
                        Notification
                                .error("Situation Awareness",
                                        e.getClass().getSimpleName()
                                                + " while polling ARGOS positions from Web.")
                                .requireHumanAction(false));
    }
}

From source file:org.kalypso.ui.KalypsoGisPlugin.java

/**
 * Returns the global format for displaying dates + times.<br/>
 * The format is preconfigured with the right display timezone (i.e. no need for extra call to {@link #getDisplayTimeZone()}.<br/>
 * <br/>//from  w  w w.ja va2s .c  om
 * TODO: replace all static date format all around the place <br/>
 * TODO: we should provide several versions: long/short, for String.format etc.<br/>
 * TODO: Let user choose hiw own format in the kalypso preference page <br/>
 */
public DateFormat getDisplayDateTimeFormat() {
    // We recreate the date format in order to support change of preferences without restart of Kalypso
    final DateFormat df = new SimpleDateFormat("dd.MM.yyyy HH:mm"); //$NON-NLS-1$
    df.setTimeZone(getDisplayTimeZone());
    return df;
}

From source file:org.apache.ivory.retention.FeedEvictor.java

@Override
public int run(String[] args) throws Exception {

    CommandLine cmd = getCommand(args);//w  w  w  . j  a  va 2s  .c  om
    String feedBasePath = cmd.getOptionValue("feedBasePath").replaceAll("\\?\\{", "\\$\\{");
    String retentionType = cmd.getOptionValue("retentionType");
    String retentionLimit = cmd.getOptionValue("retentionLimit");
    String timeZone = cmd.getOptionValue("timeZone");
    String frequency = cmd.getOptionValue("frequency"); //to write out smart path filters
    String logFile = cmd.getOptionValue("logFile");

    Path normalizedPath = new Path(feedBasePath);
    fs = normalizedPath.getFileSystem(getConf());
    feedBasePath = normalizedPath.toUri().getPath();
    LOG.info("Normalized path : " + feedBasePath);
    Pair<Date, Date> range = getDateRange(retentionLimit);
    String dateMask = getDateFormatInPath(feedBasePath);
    List<Path> toBeDeleted = discoverInstanceToDelete(feedBasePath, timeZone, dateMask, range.first);

    LOG.info("Applying retention on " + feedBasePath + " type: " + retentionType + ", Limit: " + retentionLimit
            + ", timezone: " + timeZone + ", frequency: " + frequency);

    DateFormat dateFormat = new SimpleDateFormat(format);
    dateFormat.setTimeZone(TimeZone.getTimeZone(timeZone));
    StringBuffer buffer = new StringBuffer();
    StringBuffer instancePaths = new StringBuffer("instancePaths=");
    for (Path path : toBeDeleted) {
        if (deleteInstance(path)) {
            LOG.info("Deleted instance " + path);
            Date date = getDate(path, feedBasePath, dateMask, timeZone);
            buffer.append(dateFormat.format(date)).append(',');
            instancePaths.append(path).append(",");
        }
    }

    logInstancePaths(new Path(logFile), instancePaths.toString());

    int len = buffer.length();
    if (len > 0) {
        stream.println("instances=" + buffer.substring(0, len - 1));
    } else {
        stream.println("instances=NULL");
    }

    return 0;
}

From source file:org.archive.wayback.util.StringFormatter.java

public MessageFormat getFormat(String pattern) {
    MessageFormat format = formats.get(pattern);
    if (format == null) {
        format = new MessageFormat(pattern, locale);
        // lets try to make sure any internal DateFormats use UTC:
        Format[] subFormats = format.getFormats();
        if (subFormats != null) {
            for (Format subFormat : subFormats) {
                if (subFormat instanceof DateFormat) {
                    DateFormat subDateFormat = (DateFormat) subFormat;
                    subDateFormat.setTimeZone(TZ_UTC);
                }/*www .ja  v  a  2s  . c o  m*/
            }
        }
        formats.put(pattern, format);
    }
    return format;
}

From source file:com.dsi.ant.antplus.pluginsampler.geocache.Dialog_GeoDeviceDetails.java

protected void refreshData() {
    //Set data display with current values
    if (deviceData.programmableData.identificationString != null)
        textView_IdString.setText(String.valueOf(deviceData.programmableData.identificationString));
    if (deviceData.programmableData.PIN != null)
        textView_PIN.setText(String.valueOf(deviceData.programmableData.PIN));
    if (deviceData.programmableData.latitude != null)
        textView_Latitude.setText(// w ww.j  a  v  a  2  s .  c om
                String.valueOf(deviceData.programmableData.latitude.setScale(5, BigDecimal.ROUND_HALF_UP)));
    if (deviceData.programmableData.longitude != null)
        textView_Longitude.setText(
                String.valueOf(deviceData.programmableData.longitude.setScale(5, BigDecimal.ROUND_HALF_UP)));
    if (deviceData.programmableData.hintString != null)
        textView_HintString.setText(String.valueOf(deviceData.programmableData.hintString));
    if (deviceData.programmableData.lastVisitTimestamp != null) {
        DateFormat df = DateFormat.getDateTimeInstance();
        df.setTimeZone(TimeZone.getTimeZone("UTC"));
        textView_LastVisit.setText(df.format(deviceData.programmableData.lastVisitTimestamp.getTime()));
    }
    if (deviceData.programmableData.numberOfVisits != null)
        textView_NumVisits.setText(String.valueOf(deviceData.programmableData.numberOfVisits));

    textView_HardwareVer.setText(String.valueOf(deviceData.hardwareRevision));
    textView_ManfID.setText(String.valueOf(deviceData.manufacturerID));
    textView_ModelNum.setText(String.valueOf(deviceData.modelNumber));
    textView_SoftwareVer.setText(String.valueOf(deviceData.softwareRevision));
    textView_SerialNum.setText(String.valueOf(deviceData.serialNumber));
    textView_BatteryVoltage.setText(String.valueOf(deviceData.batteryVoltage));
    textView_BatteryStatus.setText(deviceData.batteryStatus.toString());
    textView_OperatingTime.setText(String.valueOf(deviceData.cumulativeOperatingTime));
    textView_OperatingTimeResolution.setText(String.valueOf(deviceData.cumulativeOperatingTimeResolution));
}

From source file:amazon.SignedRequestsHelper.java

/**
 * Generate a ISO-8601 format timestamp as required by Amazon.
 *  //from  w  ww  . j  ava 2 s  . c  o  m
 * @return  ISO-8601 format timestamp.
 */
private String timestamp() {
    String timestamp = null;
    Calendar cal = Calendar.getInstance();
    DateFormat dfm = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
    dfm.setTimeZone(TimeZone.getTimeZone("GMT"));
    timestamp = dfm.format(cal.getTime());
    return timestamp;
}

From source file:org.nuxeo.ecm.platform.semanticentities.service.RemoteEntityServiceTest.java

@SuppressWarnings("unchecked")
@Test/*from   ww  w  . j  a  v  a  2  s  . co  m*/
public void testDerefenceRemoteEntity() throws Exception {
    DocumentModel barackDoc = session.createDocumentModel("Person");
    service.dereferenceInto(barackDoc, DBPEDIA_BARACK_OBAMA_URI, true, false);

    // the title and birth date are fetched from the remote entity
    // description
    assertEquals("Barack Obama", barackDoc.getTitle());

    String summary = barackDoc.getProperty("entity:summary").getValue(String.class);
    String expectedSummary = "Barack Hussein Obama II is the 44th and current President of the United States.";
    assertEquals(expectedSummary, summary.substring(0, expectedSummary.length()));

    List<String> altnames = barackDoc.getProperty("entity:altnames").getValue(List.class);
    assertEquals(4, altnames.size());
    // Western spelling:
    assertTrue(altnames.contains("Barack Obama"));
    // Russian spelling:
    assertTrue(altnames.contains("\u041e\u0431\u0430\u043c\u0430, \u0411\u0430\u0440\u0430\u043a"));

    Calendar birthDate = barackDoc.getProperty("person:birthDate").getValue(Calendar.class);

    TimeZone tz = TimeZone.getTimeZone("ECT");
    DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, Locale.US);
    formatter.setTimeZone(tz);
    assertEquals("August 4, 1961 1:00:00 AM CET", formatter.format(birthDate.getTime()));

    Blob depiction = barackDoc.getProperty("entity:depiction").getValue(Blob.class);
    assertNotNull(depiction);
    assertEquals("200px-Official_portrait_of_Barack_Obama.jpg", depiction.getFilename());
    assertEquals(14748, depiction.getLength());

    List<String> sameas = barackDoc.getProperty("entity:sameas").getValue(List.class);
    assertTrue(sameas.contains(DBPEDIA_BARACK_OBAMA_URI.toString()));

    // check that further dereferencing with override == false does not
    // erase local changes
    barackDoc.setPropertyValue("dc:title", "B. Obama");
    barackDoc.setPropertyValue("person:birthDate", null);

    service.dereferenceInto(barackDoc, DBPEDIA_BARACK_OBAMA_URI, false, false);

    assertEquals("B. Obama", barackDoc.getTitle());
    birthDate = barackDoc.getProperty("person:birthDate").getValue(Calendar.class);
    assertEquals("August 4, 1961 1:00:00 AM CET", formatter.format(birthDate.getTime()));

    // existing names are not re-added
    altnames = barackDoc.getProperty("entity:altnames").getValue(List.class);
    assertEquals(4, altnames.size());

    // later dereferencing with override == true does not preserve local
    // changes
    service.dereferenceInto(barackDoc, DBPEDIA_BARACK_OBAMA_URI, true, false);
    assertEquals("Barack Obama", barackDoc.getTitle());
}