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

The following are Jave code examples for showing how to use setTimeZone() of the java.text.DateFormat class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: skLib   File: ExprFormatDateOfPlayer.java   Source Code and License Vote up 7 votes
@Override
public String convert(Player o) {
	InetAddress rawIp = o.getAddress().getAddress();
	String ip = rawIp.toString().replaceAll("/", "");
	JSONObject jsonParsed = null;
	try {
		jsonParsed = JsonReader.readJsonFromUrl("http://freegeoip.net/json/" + ip);
	} catch (JSONException | IOException e) {
		e.printStackTrace();
	}
	String jsonValue = (String) jsonParsed.get("time_zone");
	Date date = new Date();
	DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
	df.setTimeZone(TimeZone.getTimeZone(jsonValue));
	return df.format(date);
}
 
Example 2
Project: mule-json-logger   File: JsonLogger.java   Source Code and License Vote up 7 votes
private void log(LogMessage logMessage, LogLevel level, String loggerName) {
	String logMessageString;
	if (config.getLogInPlainString()) {
		StringBuilder sb = new StringBuilder();
		sb.append("[CID: ").append(logMessage.getCorrelationId());
		if (StringUtils.isNotBlank(logMessage.getCorrelationIdLocal())) {
			sb.append(" CID.Local: ").append(logMessage.getCorrelationIdLocal());
		}
		sb.append("] ").append(logMessage.getMessage());
		String varsInString = LogHelper.variablesToString(logMessage.getVariables(), config.getLogVariableType());
		if (varsInString.length() > 0) {
			sb.append(" [").append(varsInString).append("]");
		}
		if (logMessage.getThrowable() != null) {
			Throwable t = logMessage.getThrowable();
			sb.append("\nException: ").append(ExceptionUtils.getMessage(t)).append(" ")
					.append(ExceptionUtils.getStackTrace(logMessage.getThrowable()));
			sb.append("");
		}
		logMessageString = sb.toString();
	} else {
		TimeZone tz = TimeZone.getTimeZone("UTC");
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
		df.setTimeZone(tz);
		logMessage.setTimestamp(df.format(new Date()));
		logMessage.setLevel(level.toString());
		logMessage.setLogger(loggerName);
		logMessage.setThread(Thread.currentThread().toString());
		Gson gson = new GsonBuilder().disableHtmlEscaping().disableHtmlEscaping().create();
		logMessageString = gson.toJson(logMessage);
	}

	Logger logger = LogManager.getLogger(loggerName);
	switch (level) {
	case INFO:
		logger.info(logMessageString);
		break;
	case ERROR:
		logger.error(logMessageString);
		break;
	case FATAL:
		logger.fatal(logMessageString);
		break;
	case DEBUG:
		logger.debug(logMessageString);
		break;
	}
}
 
Example 3
Project: GitHub   File: Bug_for_lenolix_8.java   Source Code and License Vote up 6 votes
public void test_for_objectKey() throws Exception {
    DateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", JSON.defaultLocale);
    simpleDateFormat.setTimeZone(JSON.defaultTimeZone);
    Map<Integer, User> map = new HashMap<Integer, User>();

    User user = new User();
    user.setId(1);
    user.setIsBoy(true);
    user.setName("leno.lix");
    user.setBirthDay(simpleDateFormat.parse("2012-03-07 22:38:21"));
    user.setGmtCreate(new java.sql.Date(simpleDateFormat.parse("2012-02-03 22:38:21").getTime()));

    map.put(1, user);

    String mapJson = JSON.toJSONString(map, SerializerFeature.WriteClassName, SerializerFeature.WriteMapNullValue);

    System.out.println(mapJson);

    Object object = JSON.parse(mapJson);

}
 
Example 4
Project: ipack   File: LocalizedMessage.java   Source Code and License Vote up 6 votes
protected String formatWithTimeZone(
        String template,
        Object[] arguments, 
        Locale locale,
        TimeZone timezone) 
{
    MessageFormat mf = new MessageFormat(" ");
    mf.setLocale(locale);
    mf.applyPattern(template);
    if (!timezone.equals(TimeZone.getDefault())) 
    {
        Format[] formats = mf.getFormats();
        for (int i = 0; i < formats.length; i++) 
        {
            if (formats[i] instanceof DateFormat) 
            {
                DateFormat temp = (DateFormat) formats[i];
                temp.setTimeZone(timezone);
                mf.setFormat(i,temp);
            }
        }
    }
    return mf.format(arguments);
}
 
Example 5
Project: okwallet   File: BackupWalletDialogFragment.java   Source Code and License Vote up 6 votes
private File determineBackupFile() {
    Constants.Files.EXTERNAL_WALLET_BACKUP_DIR.mkdirs();
    checkState(Constants.Files.EXTERNAL_WALLET_BACKUP_DIR.isDirectory(), "%s is not a directory",
            Constants.Files.EXTERNAL_WALLET_BACKUP_DIR);

    final DateFormat dateFormat = Iso8601Format.newDateFormat();
    dateFormat.setTimeZone(TimeZone.getDefault());

    for (int i = 0; true; i++) {
        final StringBuilder filename = new StringBuilder(Constants.Files.EXTERNAL_WALLET_BACKUP);
        filename.append('-');
        filename.append(dateFormat.format(new Date()));
        if (i > 0)
            filename.append(" (").append(i).append(')');

        final File file = new File(Constants.Files.EXTERNAL_WALLET_BACKUP_DIR, filename.toString());
        if (!file.exists())
            return file;
    }
}
 
Example 6
Project: Android_watch_magpie   File: DateFormater.java   Source Code and License Vote up 5 votes
private String getDate(long timeStamp, String dateFormat)
{

    DateFormat objFormatter = new SimpleDateFormat(dateFormat);
    String timezone= Calendar.getInstance().getTimeZone().getDefault().getDisplayName();
    objFormatter.setTimeZone(TimeZone.getTimeZone(timezone));

    Calendar objCalendar =
            Calendar.getInstance(TimeZone.getTimeZone(timezone));
    objCalendar.setTimeInMillis(timeStamp*1000);
    String formatedDate= objFormatter.format(objCalendar.getTime());
    objCalendar.clear();
    return formatedDate;
}
 
Example 7
Project: lams   File: ThreadSafeSimpleDateFormat.java   Source Code and License Vote up 5 votes
private DateFormat fetchFromPool() {
    final DateFormat format = pool.fetchFromPool();
    final TimeZone tz = timeZone != null ? timeZone : TimeZone.getDefault();
    if (!tz.equals(format.getTimeZone())) {
        format.setTimeZone(tz);
    }
    return format;
}
 
Example 8
Project: springboot-training   File: DateUtil.java   Source Code and License Vote up 5 votes
/**
 * 获取指定时区的格式
 * 
 * @return
 */
public DateFormat getFormat(String format, int timeZone) {
	DateFormat sdf = new SimpleDateFormat(format);
	TimeZone zone = TimeZone.getTimeZone(timeZone < 0 ? "GMT" + timeZone : "GMT+" + timeZone);
	sdf.setTimeZone(zone);
	return sdf;
}
 
Example 9
Project: OpenDA   File: SwanTemplateDataObjectTest.java   Source Code and License Vote up 5 votes
private double formatDate(String dateString) {
    DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
    Date startDate;

    try {
        startDate = formatter.parse(dateString);
    } catch (ParseException e) {
        throw new RuntimeException(this.getClass().getName() +
                ": could not parse time from argument \"" + dateString + "\"");
    }
    return new Time(startDate).getMJD();
}
 
Example 10
Project: openrasp   File: TimeUtils.java   Source Code and License Vote up 5 votes
/**
 * 获取ISO8601格式化时间
 *
 * @return 格式化时间
 */
public static String getISO8601FormatDate() {
    TimeZone timeZone = TimeZone.getTimeZone("UTC");
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); //"Z" to indicate UTC
    dateFormat.setTimeZone(timeZone);
    return dateFormat.format(new Date());
}
 
Example 11
Project: GitHub   File: ResponseCacheTest.java   Source Code and License Vote up 5 votes
/**
 * For Last-Modified and Date headers, we should echo the date back in the exact format we were
 * served.
 */
@Test public void retainServedDateFormat() throws Exception {
  // Serve a response with a non-standard date format that OkHttp supports.
  Date lastModifiedDate = new Date(System.currentTimeMillis() + TimeUnit.HOURS.toMillis(-1));
  Date servedDate = new Date(System.currentTimeMillis() + TimeUnit.HOURS.toMillis(-2));
  DateFormat dateFormat = new SimpleDateFormat("EEE dd-MMM-yyyy HH:mm:ss z", Locale.US);
  dateFormat.setTimeZone(TimeZone.getTimeZone("EDT"));
  String lastModifiedString = dateFormat.format(lastModifiedDate);
  String servedString = dateFormat.format(servedDate);

  // This response should be conditionally cached.
  server.enqueue(new MockResponse()
      .addHeader("Last-Modified: " + lastModifiedString)
      .addHeader("Expires: " + servedString)
      .setBody("A"));
  server.enqueue(new MockResponse()
      .setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED));

  assertEquals("A", readAscii(openConnection(server.url("/").url())));
  assertEquals("A", readAscii(openConnection(server.url("/").url())));

  // The first request has no conditions.
  RecordedRequest request1 = server.takeRequest();
  assertNull(request1.getHeader("If-Modified-Since"));

  // The 2nd request uses the server's date format.
  RecordedRequest request2 = server.takeRequest();
  assertEquals(lastModifiedString, request2.getHeader("If-Modified-Since"));
}
 
Example 12
Project: alipay-sdk   File: AlipayLogger.java   Source Code and License Vote up 5 votes
/**
 * 通讯错误日志
 */
private static void _logCommError(Exception e, HttpURLConnection conn, String url,
                                  String appKey, String method, Map<String, String> params) {
    DateFormat df = new SimpleDateFormat(AlipayConstants.DATE_TIME_FORMAT);
    df.setTimeZone(TimeZone.getTimeZone(AlipayConstants.DATE_TIMEZONE));
    String sdkName = AlipayConstants.SDK_VERSION;
    String urlStr = null;
    String rspCode = "";
    if (conn != null) {
        try {
            urlStr = conn.getURL().toString();
            rspCode = "HTTP_ERROR_" + conn.getResponseCode();
        } catch (IOException ioe) {
        }
    } else {
        urlStr = url;
        rspCode = "";
    }
    StringBuilder sb = new StringBuilder();
    sb.append(df.format(new Date()));// 时间
    sb.append("^_^");
    sb.append(method);// API
    sb.append("^_^");
    sb.append(appKey);// APP
    sb.append("^_^");
    sb.append(getIp());// IP地址
    sb.append("^_^");
    sb.append(osName);// 操作系统
    sb.append("^_^");
    sb.append(sdkName);// SDK名字,这是例子,请换成其他名字
    sb.append("^_^");
    sb.append(urlStr);// 请求URL
    sb.append("^_^");
    sb.append(rspCode);
    sb.append("^_^");
    sb.append((e.getMessage() + "").replaceAll("\r\n", " "));
    clog.error(sb.toString());
}
 
Example 13
Project: GitHub   File: UrlConnectionCacheTest.java   Source Code and License Vote up 5 votes
/**
 * For Last-Modified and Date headers, we should echo the date back in the exact format we were
 * served.
 */
@Test public void retainServedDateFormat() throws Exception {
  // Serve a response with a non-standard date format that OkHttp supports.
  Date lastModifiedDate = new Date(System.currentTimeMillis() + TimeUnit.HOURS.toMillis(-1));
  Date servedDate = new Date(System.currentTimeMillis() + TimeUnit.HOURS.toMillis(-2));
  DateFormat dateFormat = new SimpleDateFormat("EEE dd-MMM-yyyy HH:mm:ss z", Locale.US);
  dateFormat.setTimeZone(TimeZone.getTimeZone("EDT"));
  String lastModifiedString = dateFormat.format(lastModifiedDate);
  String servedString = dateFormat.format(servedDate);

  // This response should be conditionally cached.
  server.enqueue(new MockResponse()
      .addHeader("Last-Modified: " + lastModifiedString)
      .addHeader("Expires: " + servedString)
      .setBody("A"));
  server.enqueue(new MockResponse()
      .setResponseCode(HttpURLConnection.HTTP_NOT_MODIFIED));

  assertEquals("A", readAscii(urlFactory.open(server.url("/").url())));
  assertEquals("A", readAscii(urlFactory.open(server.url("/").url())));

  // The first request has no conditions.
  RecordedRequest request1 = server.takeRequest();
  assertNull(request1.getHeader("If-Modified-Since"));

  // The 2nd request uses the server's date format.
  RecordedRequest request2 = server.takeRequest();
  assertEquals(lastModifiedString, request2.getHeader("If-Modified-Since"));
}
 
Example 14
Project: alipay-sdk   File: AlipayLogger.java   Source Code and License Vote up 5 votes
/**
 * 发生特别错误时记录完整错误现场
 */
public static void logErrorScene(Map<String, Object> rt, AlipayResponse tRsp,
                                 String appSecret) {
    if (!needEnableLogger) {
        return;
    }
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    df.setTimeZone(TimeZone.getTimeZone(AlipayConstants.DATE_TIMEZONE));
    StringBuilder sb = new StringBuilder();
    sb.append("ErrorScene");
    sb.append("^_^");
    sb.append(tRsp.getErrorCode());
    sb.append("^_^");
    sb.append(tRsp.getSubCode());
    sb.append("^_^");
    sb.append(ip);
    sb.append("^_^");
    sb.append(osName);
    sb.append("^_^");
    sb.append(df.format(new Date()));
    sb.append("^_^");
    sb.append("ProtocalMustParams:");
    appendLog((AlipayHashMap) rt.get("protocalMustParams"), sb);
    sb.append("^_^");
    sb.append("ProtocalOptParams:");
    appendLog((AlipayHashMap) rt.get("protocalOptParams"), sb);
    sb.append("^_^");
    sb.append("ApplicationParams:");
    appendLog((AlipayHashMap) rt.get("textParams"), sb);
    sb.append("^_^");
    sb.append("Body:");
    sb.append((String) rt.get("rsp"));
    blog.error(sb.toString());
}
 
Example 15
Project: opencps-v2   File: APIDateTimeUtils.java   Source Code and License Vote up 5 votes
public static String convertDateToString(Date date, String pattern) {
	DateFormat dateFormat = DateFormatFactoryUtil.getSimpleDateFormat(
		pattern);

	if (Validator.isNull(date) || Validator.isNull(pattern)) {
		return StringPool.BLANK;
	}

	dateFormat.setTimeZone(TimeZoneUtil.getTimeZone("Asia/Ho_Chi_Minh"));

	Calendar calendar = Calendar.getInstance();

	calendar.setTime(date);

	return dateFormat.format(calendar.getTime());
}
 
Example 16
Project: opencps-v2   File: DateTimeUtils.java   Source Code and License Vote up 4 votes
public static String convertDateToString(Date date, String pattern) {
	DateFormat dateFormat = DateFormatFactoryUtil.getSimpleDateFormat(
		pattern);

	if (Validator.isNull(date) || Validator.isNull(pattern)) {
		return StringPool.BLANK;
	}

	dateFormat.setTimeZone(TimeZoneUtil.getTimeZone("Asia/Ho_Chi_Minh"));

	Calendar calendar = Calendar.getInstance();

	calendar.setTime(date);

	return dateFormat.format(calendar.getTime());
}
 
Example 17
Project: lazycat   File: DateTool.java   Source Code and License Vote up 4 votes
@Override
public DateFormat initialValue() {
	DateFormat result = new SimpleDateFormat(OLD_COOKIE_PATTERN, Locale.US);
	result.setTimeZone(GMT_ZONE);
	return result;
}
 
Example 18
Project: GitHub   File: UrlConnectionCacheTest.java   Source Code and License Vote up 4 votes
private String formatDate(Date date) {
  DateFormat rfc1123 = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US);
  rfc1123.setTimeZone(TimeZone.getTimeZone("GMT"));
  return rfc1123.format(date);
}
 
Example 19
Project: opencps-v2   File: DateTimeUtils.java   Source Code and License Vote up 4 votes
public static String convertDateToString(Date date, String pattern) {
	DateFormat dateFormat = DateFormatFactoryUtil.getSimpleDateFormat(
		pattern);

	if (Validator.isNull(date) || Validator.isNull(pattern)) {
		return StringPool.BLANK;
	}

	dateFormat.setTimeZone(TimeZoneUtil.getTimeZone("Asia/Ho_Chi_Minh"));

	Calendar calendar = Calendar.getInstance();

	calendar.setTime(date);

	return dateFormat.format(calendar.getTime());
}
 
Example 20
Project: GitHub   File: ResponseCacheTest.java   Source Code and License Vote up 4 votes
private String formatDate(Date date) {
  DateFormat rfc1123 = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US);
  rfc1123.setTimeZone(TimeZone.getTimeZone("GMT"));
  return rfc1123.format(date);
}