问题描述
限时送ChatGPT账号..是否可以使用 SimpleDateFormat 类在 Java 中格式化日期时间以给出日期的时区部分,而后不带 +0000.
Is it possible to format a date time in Java using the SimpleDateFormat class to give the timezone part of a date without having the +0000 after it.
编辑
我们正在更改 Java 中的默认时区,如下所示:
We are changing the Default Timezone within Java as follows:
SimpleTimeZone tz = new SimpleTimeZone(0, "Out Timezone");
TimeZone.setDefault(tz);
不幸的是,我无法删除此代码.我会冒险猜测整个系统停止工作.我认为最初的作者将其用于解决一些夏令时问题.
Unfortunately, I am in no position to remove this code. I would hazard a guess at the whole system stopping working. I think the initial author put this in to work around some day light saving issues.
考虑到这一点,我想将日期格式化为:
With this in mind, I want to format the date as:
2011-12-27 09:00 GMT
或
2011-12-27 09:00 BST
我只能让 SimpleDateFormat 输出为:
I can only get the SimpleDateFormat to output as:
2011-12-27 09:00:00 GMT+00:00
2011-12-27 09:00:00 GMT+00:00
使用格式字符串 yyyy-MM-dd HH:mm:ss z
我在任何地方都看不到简单时区引用了冬季时间 (GMT) id 或夏季时间 id (BST).
I cannot see anywhere where the simple timezone has any reference to winter time (GMT) id or summer time id (BST).
推荐答案
根本不是一个优雅的解决方案,但它对我们有用.我必须为 DateFormat/SimpleDateFormat 创建一个自定义实现.这看起来像下面这样:
Not an elegant solution at all but it works for us. I had to create a custom implementation for DateFormat/SimpleDateFormat. This looks like something as follows:
static {
// this would be initialized like something as follows when the application starts
// which causes the headaches of SimpleDateFormat not to work...
SimpleTimeZone tz = new SimpleTimeZone(0, "Out Timezone");
TimeZone.setDefault(tz);
}
// therefore this class will workaround the issue,
public class OurOwnCustomDateFormat
extends SimpleDateFormat {
/** The pattern to use as the format string. */
protected String pattern;
public OurOwnCustomDateFormat(String pattern) {
super(pattern);
// store the pattern
this.pattern = pattern;
}
@Override
public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition pos) {
// custom implementation to format the date and time based on our TimeZone
toAppendTo.insert(pos.getBeginIndex(), "the date with our custom format calculated here");
return toAppendTo;
}
这篇关于自定义时区的 Java (GMT+00:00) 中没有时区偏移的 SimpleDateFormat的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论