java-在日期格式化后以小写形式显示AM和PM
格式化日期时间后,时间以大写形式显示AM或PM,但我希望以小写形式显示,例如am或pm。
这是我的代码:
public class Timeis {
public static void main(String s[]) {
long ts = 1022895271767L;
String st = null;
st = new SimpleDateFormat(" MMM d 'at' hh:mm a").format(ts);
System.out.println("time is " + ts);
}
}
7个解决方案
79 votes
这有效
public class Timeis {
public static void main(String s[]) {
long ts = 1022895271767L;
SimpleDateFormat sdf = new SimpleDateFormat(" MMM d 'at' hh:mm a");
// CREATE DateFormatSymbols WITH ALL SYMBOLS FROM (DEFAULT) Locale
DateFormatSymbols symbols = new DateFormatSymbols(Locale.getDefault());
// OVERRIDE SOME symbols WHILE RETAINING OTHERS
symbols.setAmPmStrings(new String[] { "am", "pm" });
sdf.setDateFormatSymbols(symbols);
String st = sdf.format(ts);
System.out.println("time is " + st);
}
}
James Jithin answered 2019-10-08T19:46:10Z
63 votes
不幸的是,标准格式设置方法不允许您这样做。 乔达也没有。 我认为您将必须通过简单的后格式替换来处理格式日期。
String str = oldstr.replace("AM", "am").replace("PM","pm");
您可以使用使用regepxs的replaceAll()方法,但是我认为以上方法就足够了。 我没有做toLowerCase(),因为如果将来更改格式字符串以包含(例如)月份名称或类似名称,可能会破坏格式。
编辑:James Jithin的解决方案看起来好得多,并且执行此操作的正确方法(如评论中所述)
Brian Agnew answered 2019-10-08T19:45:46Z
6 votes
试试这个:
System.out.println("time is " + ts.toLowerCase());
虽然您可以按照此处和此处的说明创建自定义格式
不幸的是,AM和PM似乎无法在标准SimpleDateFormat类中自定义
RNJ answered 2019-10-08T19:46:41Z
4 votes
如果您不想执行字符串替换,并且正在使用Java 8 DateTimeFormatter:
Map ampm = new HashMap<>();
ampm.put(0l, "am");
ampm.put(1l, "pm");
DateTimeFormatter dtf = new DateTimeFormatterBuilder()
.appendPattern("E M/d h:mm")
.appendText(ChronoField.AMPM_OF_DAY, ampm)
.toFormatter()
.withZone(ZoneId.of("America/Los_Angeles"));
必须手动构建DateTimeFormatter(指定单个片段),因为没有用于小写am / pm的图案符号。 您可以在之前和之后使用appendPattern。
我相信没有办法替代默认的am / pm符号,这是唯一的一种在最终字符串上进行字符串替换的方法。
Nikola Mihajlović answered 2019-10-08T19:47:20Z
3 votes
Calendar c = Calendar.getInstance();
System.out.println("Current time => " + c.getTime());
SimpleDateFormat df = new SimpleDateFormat("HH:mm a");
String formattedDate = df.format(c.getTime());
formattedDate = formattedDate.replace("a.m.", "AM").replace("p.m.","PM");
TextView textView = findViewById(R.id.textView);
textView.setText(formattedDate);
Mourya answered 2019-10-08T19:47:37Z
1 votes
如果您想要默认am,pm以外的其他样式,James的答案很好。 但是,恐怕您需要在Locale和特定于Locale的AM / PM集之间进行映射才能采用覆盖。 现在,您只需使用Java内置的java.util.Formatter类。 因此,一个简单的示例如下所示:
System.out.println(String.format(Locale.UK, "%1$tl%1$tp", LocalTime.now()));
它给:
9pm
注意,如果要大写,只需将“%1 $ tp”替换为“%1 $ Tp”。 您可以在[http://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html#dt]中找到更多详细信息。
ShenYi answered 2019-10-08T19:48:11Z
0 votes
只需添加toUpperCase()这样
public class Timeis {
public static void main(String s[]) {
long ts = 1022895271767L;
String st = null;
st = new SimpleDateFormat(" MMM d 'at' hh:mm a").format(ts).toLowerCase();
System.out.println("time is " + ts);
}
}
和toUpperCase()(如果要大写)
3zcs answered 2019-10-08T19:48:42Z