Java Code Examples for java.text.DateFormat#setTimeZone()

The following examples show how to use java.text.DateFormat#setTimeZone() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: ALLGO   File: DateUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 
 * @param time1 	需要转换的时间数据
 * @param source 	输入格式
 * @param result 	输出格式
 * @return
 */
public static String showDate(String time1 , String source ,String result) {
	String str = "";
	if(!time1.equals("")){
		SimpleDateFormat sf = new SimpleDateFormat(source , Locale.ENGLISH);
		sf.setTimeZone(TimeZone.getTimeZone("GMT+08:00"));
		Date date = null;
		try {
			date = sf.parse(time1);
		} catch (ParseException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		DateFormat sdf = new SimpleDateFormat(result , Locale.ENGLISH);
		sdf.setTimeZone(TimeZone.getTimeZone("GMT+08:00")); // 设置时区为GMT+08:00 
		    str = sdf.format(date);
	}
	return str;
}
 
Example 2
Source Project: openapi-generator   File: ApiClientTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testParseAndFormatDate() {
    // default date format
    String dateStr = "2015-11-07T03:49:09.356Z";
    assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09.356+00:00")));
    assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09.356Z")));
    assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T05:49:09.356+02:00")));
    assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T02:49:09.356-01:00")));

    // custom date format: without milli-seconds, custom time zone
    DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX", Locale.ROOT);
    format.setTimeZone(TimeZone.getTimeZone("GMT+10"));
    apiClient.setDateFormat(format);
    dateStr = "2015-11-07T13:49:09+10:00";
    assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09+00:00")));
    assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09Z")));
    assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T00:49:09-03:00")));
    assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T13:49:09+10:00")));
}
 
Example 3
Source Project: megan-ce   File: Biom1Data.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * constructor to be used when generating new biome files
 *
 * @param id
 */
public Biom1Data(String id) {
    this.id = id;
    format = "Biological Observation Matrix 1.0.0";
    format_url = "http://biom-format.org";
    generated_by = ProgramProperties.getProgramName();
    TimeZone tz = TimeZone.getTimeZone("UTC");
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    df.setTimeZone(tz);
    date = df.format(new Date());
}
 
Example 4
/**
 * Final initialization, once all dependencies are set.
 */
public void init()
{
	Objects.requireNonNull(userLocaleService);
	Objects.requireNonNull(userTimeService);
	/** The time zone for our GMT times. */
	M_tz = TimeZone.getTimeZone("GMT");

	log.info("init()");

	/**
	 * a calendar to clone for GMT time construction
	 */
	M_GCal = newCalendar(M_tz, 0, 0, 0, 0, 0, 0, 0);

	// Note: formatting for GMT time representations
	M_fmtA = (DateFormat)(new SimpleDateFormat("yyyyMMddHHmmssSSS"));
	M_fmtB = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT);
	M_fmtC = DateFormat.getTimeInstance(DateFormat.SHORT);
	M_fmtD = DateFormat.getDateInstance(DateFormat.MEDIUM);
	M_fmtE = (DateFormat)(new SimpleDateFormat("yyyyMMddHHmmss"));
	M_fmtG = (DateFormat)(new SimpleDateFormat("yyyy/DDD/HH/")); // that's year, day of year, hour

	M_fmtA.setTimeZone(M_tz);
	M_fmtB.setTimeZone(M_tz);
	M_fmtC.setTimeZone(M_tz);
	M_fmtD.setTimeZone(M_tz);
	M_fmtE.setTimeZone(M_tz);
	M_fmtG.setTimeZone(M_tz);

}
 
Example 5
/**
 * Static method to get date-time DateFormat for input.  This is based on a 2 digit year
 * input mask, which also handles 4-digit year, but caller must use doParseDate() to
 * handle single-digit years, out-of-bounds years, and trailing garbage in input string.
 * DateFormat.LONG uses short-date and long-time formats
 * 
 * @param locale locale
 * @param tz time zone
 * @param style DateFormat style
 * @return a date and time DateFormat.
 */

public static DateFormat getLocaleInputDateTimeFormat(Locale locale, int style, TimeZone tz) {
	    DateFormat df;
	    switch (style) {
        case DateFormat.SHORT :
            df= getFormatProvider(locale).getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, locale);
            break;
        case DateFormat.MEDIUM :
            df = getFormatProvider(locale).getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, locale);
            break;
        case DateFormat.LONG :
            df = getFormatProvider(locale).getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG, locale);
            break;
        default :
            df = getFormatProvider(locale).getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, locale);
	    
	    }
	    	 
    df.setLenient(false);
    df.setTimeZone(tz);
    Calendar calendar = df.getCalendar();
    calendar.set(Calendar.YEAR, 1959);  // 60 means 1960, 59 means 2059
    calendar.set(Calendar.MONTH, calendar.getActualMaximum(Calendar.MONTH));
    calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
    calendar.set(Calendar.HOUR_OF_DAY, calendar.getActualMaximum(Calendar.HOUR_OF_DAY));
    calendar.set(Calendar.MINUTE, calendar.getActualMinimum(Calendar.MINUTE));
    
    assert (df instanceof SimpleDateFormat);
    ((SimpleDateFormat)df).set2DigitYearStart(calendar.getTime());
    return df;
}
 
Example 6
/**
 * A numerical values representing the time at which the maximum 
 * expected intensity of precipitation occurs.
 * For more information refer to the API Docs:
 * <a href="https://developer.forecast.io">https://developer.forecast.io</a>
 * @return An human-readable time string formated as [HH:mm:ss]  Returns "no data" if the field is not defined.
 */
public String precipIntensityMaxTime(){
	if(this.datapoint.containsKey("precipIntensityMaxTime")){
		DateFormat dfm = new SimpleDateFormat("HH:mm:ss");
		dfm.setTimeZone(TimeZone.getTimeZone(timezone));
		String time = dfm.format( Long.parseLong(String.valueOf(this.datapoint.get("precipIntensityMaxTime"))) * 1000 );
		return time;
	}
	else
		return "no data";
}
 
Example 7
/**
 * Create a String time stamp for this event
 * @return a timestamp
 */
default String setTimeStamp() {
    Instant now = Instant.now();
    Timestamp current = Timestamp.from(now);
    DateFormat df = DateFormat.getDateTimeInstance();
    df.setTimeZone(TimeZone.getTimeZone("UTC"));
    return df.format(current);
}
 
Example 8
@Override
public String dateTimeFormat(Date date, Locale locale, int df) {
    if (date == null || locale == null) return "";
    log.debug("dateTimeFormat: {}, {}, {}", date.toString(), locale.toString(), df);

    DateFormat dsf = DateFormat.getDateTimeInstance(df, df, locale);
    dsf.setTimeZone(getLocalTimeZone());
    return dsf.format(date);
}
 
Example 9
Source Project: AndroidCameraUtil   File: DateParser.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Converts a Date object to a string representation.
 * @param date
 * @return date as String
 */
public static String dateToString(Date date) {
	if (date == null) {
		return null;
	} else {
		DateFormat df = new SimpleDateFormat(dateFormat);
		df.setTimeZone(utc);
		return df.format(date);	
	}
}
 
Example 10
Source Project: pay   File: AlipayHashMap.java    License: Apache License 2.0 5 votes vote down vote up
public String put(String key, Object value) {
	String strValue;

	if (value == null) {
		strValue = null;
	} else if (value instanceof String) {
		strValue = (String) value;
	} else if (value instanceof Integer) {
		strValue = ((Integer) value).toString();
	} else if (value instanceof Long) {
		strValue = ((Long) value).toString();
	} else if (value instanceof Float) {
		strValue = ((Float) value).toString();
	} else if (value instanceof Double) {
		strValue = ((Double) value).toString();
	} else if (value instanceof Boolean) {
		strValue = ((Boolean) value).toString();
	} else if (value instanceof Date) {
           DateFormat format = new SimpleDateFormat(AlipayConstants.DATE_TIME_FORMAT);
           format.setTimeZone(TimeZone.getTimeZone(AlipayConstants.DATE_TIMEZONE));
		strValue = format.format((Date) value);
	} else {
		strValue = value.toString();
	}

	return this.put(key, strValue);
}
 
Example 11
@Override
public String dateFormat(Date date, Locale locale, int df) {
    if (date == null || locale == null) return "";
    log.debug("dateFormat: {}, {}, {}", date.toString(), locale.toString(), df);

    DateFormat dsf = DateFormat.getDateInstance(df, locale);
    dsf.setTimeZone(getLocalTimeZone());
    return dsf.format(date); 
}
 
Example 12
Source Project: Tomcat7.0.67   File: DateTool.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public DateFormat initialValue() {
    DateFormat result = new SimpleDateFormat(rfc1036Pattern, Locale.US);
    result.setTimeZone(GMT_ZONE);
    return result;
}
 
Example 13
/**
 * Tests for LANG-59
 *
 * see http://issues.apache.org/jira/browse/LANG-59
 */
@Test
public void testTruncateLang59() throws Exception {
    if (!SystemUtils.isJavaVersionAtLeast(JAVA_1_4)) {
        this.warn("WARNING: Test for LANG-59 not run since the current version is " + SystemUtils.JAVA_SPECIFICATION_VERSION);
        return;
    }

    // Set TimeZone to Mountain Time
    TimeZone MST_MDT = TimeZone.getTimeZone("MST7MDT");
    TimeZone.setDefault(MST_MDT);
    DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS z");
    format.setTimeZone(MST_MDT);

    Date oct31_01MDT = new Date(1099206000000L); 

    Date oct31MDT             = new Date(oct31_01MDT.getTime()       - 3600000L); // - 1 hour
    Date oct31_01_02MDT       = new Date(oct31_01MDT.getTime()       + 120000L);  // + 2 minutes
    Date oct31_01_02_03MDT    = new Date(oct31_01_02MDT.getTime()    + 3000L);    // + 3 seconds
    Date oct31_01_02_03_04MDT = new Date(oct31_01_02_03MDT.getTime() + 4L);       // + 4 milliseconds

    assertEquals("Check 00:00:00.000", "2004-10-31 00:00:00.000 MDT", format.format(oct31MDT));
    assertEquals("Check 01:00:00.000", "2004-10-31 01:00:00.000 MDT", format.format(oct31_01MDT));
    assertEquals("Check 01:02:00.000", "2004-10-31 01:02:00.000 MDT", format.format(oct31_01_02MDT));
    assertEquals("Check 01:02:03.000", "2004-10-31 01:02:03.000 MDT", format.format(oct31_01_02_03MDT));
    assertEquals("Check 01:02:03.004", "2004-10-31 01:02:03.004 MDT", format.format(oct31_01_02_03_04MDT));

    // ------- Demonstrate Problem -------
    Calendar gval = Calendar.getInstance();
    gval.setTime(new Date(oct31_01MDT.getTime()));
    gval.set(Calendar.MINUTE, gval.get(Calendar.MINUTE)); // set minutes to the same value
    assertEquals("Demonstrate Problem", gval.getTime().getTime(), oct31_01MDT.getTime() + 3600000L);

    // ---------- Test Truncate ----------
    assertEquals("Truncate Calendar.MILLISECOND",
            oct31_01_02_03_04MDT, DateUtils.truncate(oct31_01_02_03_04MDT, Calendar.MILLISECOND));

    assertEquals("Truncate Calendar.SECOND",
               oct31_01_02_03MDT, DateUtils.truncate(oct31_01_02_03_04MDT, Calendar.SECOND));

    assertEquals("Truncate Calendar.MINUTE",
                  oct31_01_02MDT, DateUtils.truncate(oct31_01_02_03_04MDT, Calendar.MINUTE));

    assertEquals("Truncate Calendar.HOUR_OF_DAY",
                     oct31_01MDT, DateUtils.truncate(oct31_01_02_03_04MDT, Calendar.HOUR_OF_DAY));

    assertEquals("Truncate Calendar.HOUR",
                     oct31_01MDT, DateUtils.truncate(oct31_01_02_03_04MDT, Calendar.HOUR));

    assertEquals("Truncate Calendar.DATE",
                        oct31MDT, DateUtils.truncate(oct31_01_02_03_04MDT, Calendar.DATE));


    // ---------- Test Round (down) ----------
    assertEquals("Round Calendar.MILLISECOND",
            oct31_01_02_03_04MDT, DateUtils.round(oct31_01_02_03_04MDT, Calendar.MILLISECOND));

    assertEquals("Round Calendar.SECOND",
               oct31_01_02_03MDT, DateUtils.round(oct31_01_02_03_04MDT, Calendar.SECOND));

    assertEquals("Round Calendar.MINUTE",
                  oct31_01_02MDT, DateUtils.round(oct31_01_02_03_04MDT, Calendar.MINUTE));

    assertEquals("Round Calendar.HOUR_OF_DAY",
                     oct31_01MDT, DateUtils.round(oct31_01_02_03_04MDT, Calendar.HOUR_OF_DAY));

    assertEquals("Round Calendar.HOUR",
                     oct31_01MDT, DateUtils.round(oct31_01_02_03_04MDT, Calendar.HOUR));

    assertEquals("Round Calendar.DATE",
                        oct31MDT, DateUtils.round(oct31_01_02_03_04MDT, Calendar.DATE));

    // restore default time zone
    TimeZone.setDefault(defaultZone);
}
 
Example 14
@Override
public void onTrigger(final ReportingContext context) {

    final boolean isClustered = context.isClustered();
    final String nodeId = context.getClusterNodeIdentifier();
    if (nodeId == null && isClustered) {
        getLogger().debug("This instance of NiFi is configured for clustering, but the Cluster Node Identifier is not yet available. "
            + "Will wait for Node Identifier to be established.");
        return;
    }

    final BulletinQuery bulletinQuery = new BulletinQuery.Builder().after(lastSentBulletinId).build();
    final List<Bulletin> bulletins = context.getBulletinRepository().findBulletins(bulletinQuery);

    if(bulletins == null || bulletins.isEmpty()) {
        getLogger().debug("No events to send because no events are stored in the repository.");
        return;
    }

    final OptionalLong opMaxId = bulletins.stream().mapToLong(t -> t.getId()).max();
    final Long currMaxId = opMaxId.isPresent() ? opMaxId.getAsLong() : -1;

    if(currMaxId < lastSentBulletinId){
        getLogger().warn("Current bulletin max id is {} which is less than what was stored in state as the last queried event, which was {}. "
                + "This means the bulletins repository restarted its ids. Restarting querying from the beginning.", new Object[]{currMaxId, lastSentBulletinId});
        lastSentBulletinId = -1;
    }

    if (currMaxId == lastSentBulletinId) {
        getLogger().debug("No events to send due to the current max id being equal to the last id that was sent.");
        return;
    }

    final String platform = context.getProperty(SiteToSiteUtils.PLATFORM).evaluateAttributeExpressions().getValue();
    final Boolean allowNullValues = context.getProperty(ALLOW_NULL_VALUES).asBoolean();

    final Map<String, ?> config = Collections.emptyMap();
    final JsonBuilderFactory factory = Json.createBuilderFactory(config);
    final JsonObjectBuilder builder = factory.createObjectBuilder();

    final DateFormat df = new SimpleDateFormat(TIMESTAMP_FORMAT);
    df.setTimeZone(TimeZone.getTimeZone("Z"));

    final long start = System.nanoTime();

    // Create a JSON array of all the events in the current batch
    final JsonArrayBuilder arrayBuilder = factory.createArrayBuilder();
    for (final Bulletin bulletin : bulletins) {
        if(bulletin.getId() > lastSentBulletinId) {
            arrayBuilder.add(serialize(factory, builder, bulletin, df, platform, nodeId, allowNullValues));
        }
    }
    final JsonArray jsonArray = arrayBuilder.build();

    // Send the JSON document for the current batch
    Transaction transaction = null;
    try {
        // Lazily create SiteToSiteClient to provide a StateManager
        setup(context);

        transaction = getClient().createTransaction(TransferDirection.SEND);
        if (transaction == null) {
            getLogger().info("All destination nodes are penalized; will attempt to send data later");
            return;
        }

        final Map<String, String> attributes = new HashMap<>();
        final String transactionId = UUID.randomUUID().toString();
        attributes.put("reporting.task.transaction.id", transactionId);
        attributes.put("reporting.task.name", getName());
        attributes.put("reporting.task.uuid", getIdentifier());
        attributes.put("reporting.task.type", this.getClass().getSimpleName());
        attributes.put("mime.type", "application/json");

        sendData(context, transaction, attributes, jsonArray);
        transaction.confirm();
        transaction.complete();

        final long transferMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start);
        getLogger().info("Successfully sent {} Bulletins to destination in {} ms; Transaction ID = {}; First Event ID = {}",
                new Object[]{bulletins.size(), transferMillis, transactionId, bulletins.get(0).getId()});
    } catch (final Exception e) {
        if (transaction != null) {
            transaction.error();
        }
        if (e instanceof ProcessException) {
            throw (ProcessException) e;
        } else {
            throw new ProcessException("Failed to send Bulletins to destination due to IOException:" + e.getMessage(), e);
        }
    }

    lastSentBulletinId = currMaxId;
}
 
Example 15
@Override
protected DateFormat initialValue() {
    DateFormat df = new SimpleDateFormat(COOKIE_DATE_PATTERN, Locale.US);
    df.setTimeZone(TimeZone.getTimeZone("GMT"));
    return df;
}
 
Example 16
public Map<String, String> processResult(final ResultSet rs) throws SQLException {
    final String sakaiToolId = rs.getString("sakaiToolId");

    if (isHidden(rs)) {
        return null;
    }

    if (!this.subnavData.containsKey(sakaiToolId)) {
        this.subnavData.put(sakaiToolId, new ArrayList<>());
    }
    
    final Map<String, String> subnavItem = new HashMap<>();

    subnavItem.put("toolId", rs.getString("sakaiToolId"));
    subnavItem.put("siteId", rs.getString("sakaiSiteId"));
    subnavItem.put("sakaiPageId", rs.getString("sakaiPageId"));
    subnavItem.put("itemId", rs.getString("itemId"));
    subnavItem.put("sendingPage", rs.getString("itemSakaiId"));
    subnavItem.put("name", rs.getString("itemName"));
    subnavItem.put("description", rs.getString("itemDescription"));
    subnavItem.put("hidden", rs.getInt("pageHidden") == 1 ? "true" : "false");

    subnavItem.put("required", rs.getInt("required") == 1 ? "true" : "false");
    subnavItem.put("completed", rs.getInt("completed") == 1 ? "true" : "false");
    subnavItem.put("prerequisite", rs.getInt("prerequisite") == 1 ? "true" : "false");

    if (rs.getTimestamp("pageReleaseDate") != null) {
        final Timestamp releaseDate = rs.getTimestamp("pageReleaseDate");
        if (releaseDate.getTime() > System.currentTimeMillis()) {
            subnavItem.put("hidden", "true");
            final DateFormat df = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, rb.getLocale());
            final TimeZone tz = TimeService.getLocalTimeZone();
            df.setTimeZone(tz);
            subnavItem.put("releaseDate", df.format(releaseDate));
        }
    }

    this.subnavData.get(sakaiToolId).add(subnavItem);

    return subnavItem;
}
 
Example 17
Source Project: nifi   File: TestWriteAvroResult.java    License: Apache License 2.0 4 votes vote down vote up
private void testLogicalTypes(Schema schema) throws ParseException, IOException {
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();

    final List<RecordField> fields = new ArrayList<>();
    fields.add(new RecordField("timeMillis", RecordFieldType.TIME.getDataType()));
    fields.add(new RecordField("timeMicros", RecordFieldType.TIME.getDataType()));
    fields.add(new RecordField("timestampMillis", RecordFieldType.TIMESTAMP.getDataType()));
    fields.add(new RecordField("timestampMicros", RecordFieldType.TIMESTAMP.getDataType()));
    fields.add(new RecordField("date", RecordFieldType.DATE.getDataType()));
    fields.add(new RecordField("decimal", RecordFieldType.DECIMAL.getDecimalDataType(5,2)));
    final RecordSchema recordSchema = new SimpleRecordSchema(fields);

    final String expectedTime = "2017-04-04 14:20:33.789";
    final DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
    df.setTimeZone(TimeZone.getTimeZone("gmt"));
    final long timeLong = df.parse(expectedTime).getTime();

    final Map<String, Object> values = new HashMap<>();
    values.put("timeMillis", new Time(timeLong));
    values.put("timeMicros", new Time(timeLong));
    values.put("timestampMillis", new Timestamp(timeLong));
    values.put("timestampMicros", new Timestamp(timeLong));
    values.put("date", new Date(timeLong));
    values.put("decimal", new BigDecimal("123.45"));
    final Record record = new MapRecord(recordSchema, values);

    try (final RecordSetWriter writer = createWriter(schema, baos)) {
        writer.write(RecordSet.of(record.getSchema(), record));
    }

    final byte[] data = baos.toByteArray();

    try (final InputStream in = new ByteArrayInputStream(data)) {
        final GenericRecord avroRecord = readRecord(in, schema);
        final long secondsSinceMidnight = 33 + (20 * 60) + (14 * 60 * 60);
        final long millisSinceMidnight = (secondsSinceMidnight * 1000L) + 789;

        assertEquals((int) millisSinceMidnight, avroRecord.get("timeMillis"));
        assertEquals(millisSinceMidnight * 1000L, avroRecord.get("timeMicros"));
        assertEquals(timeLong, avroRecord.get("timestampMillis"));
        assertEquals(timeLong * 1000L, avroRecord.get("timestampMicros"));
        // Double value will be converted into logical decimal if Avro schema is defined as logical decimal.
        final Schema decimalSchema = schema.getField("decimal").schema();
        final LogicalType logicalType = decimalSchema.getLogicalType() != null
                ? decimalSchema.getLogicalType()
                // Union type doesn't return logical type. Find the first logical type defined within the union.
                : decimalSchema.getTypes().stream().map(s -> s.getLogicalType()).filter(Objects::nonNull).findFirst().get();
        final BigDecimal decimal = new Conversions.DecimalConversion().fromBytes((ByteBuffer) avroRecord.get("decimal"), decimalSchema, logicalType);
        assertEquals(new BigDecimal("123.45"), decimal);
    }
}
 
Example 18
@Override protected DateFormat initialValue() {
  DateFormat rfc1123 = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US);
  rfc1123.setTimeZone(TimeZone.getTimeZone("GMT"));
  return rfc1123;
}
 
Example 19
/**
 * This form of getLocalDateTimeFormat is used to render times in a specific locale. Used to send event notification emails
 * 
 * @param locale locale
 * @param tz time zone
 * @return a DateFormat instance with short time format
 */
public static DateFormat getLocaleTimeFormat(Locale locale, TimeZone tz) {
    DateFormat df = getFormatProvider(locale).getTimeInstance(DateFormat.SHORT, locale);
    df.setLenient(false);
    df.setTimeZone(tz);
    return df;
}
 
Example 20
/**
 * Get time from a Calendar with specific TimeZone
 * @param c Calendar
 * @param z TimeZone
 * @return Time String
 */
public static String getCalendarStringTime(Calendar c, TimeZone z) {
	DateFormat dfm = new SimpleDateFormat("HH:mm:ss");
	dfm.setTimeZone(z);
	return dfm.format(c.getTime());
}