我希望以24小时格式获取日期,但无法找到任何内容。
我试了这个没有运气:
System.out.println(DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT).format(Calendar.getInstance().getTime()));
但它会打印出来 28/05/14 03:57 PM
而不是 28/05/14 15:57如何在没有AM / PM和24小时格式的情况下打印小时?
答案 0 :(得分:2)
DateFormat.getDateTimeInstance()也可以有三个参数。第三个参数指定了某些习俗(如时间格式)很常见的区域(如果在大多数国家/地区采用24小时风格,或者更像是美国的上午/下午风格)。
通过选择显式语言环境,您可以以与语言环境相关的方式控制格式对象的行为。在给定有关日期样式,时间样式和区域设置的信息的情况下,Java内部将为您选择正确的格式模式。
如果这还不够,您可以考虑使用SimpleDateFormat
。然后你自己决定选择哪种确切的格式模式,但这是固定的。如果您对Java认为给定语言环境的正确格式不满意,但也想要本地化解决方案,您也可以考虑两种方法的组合:
DateFormat df;
if (locale.equals(myLocale)) {
df = new SimpleDateFormat("dd/MM/yy HH:mm"); // yy for 2-digit-year, not YY!
} else {
// general solution for other locales
df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, myLocale);
}
答案 1 :(得分:2)
answer by Meno Hochschild是正确的。
仅供参考,这是同一种解决方案,但使用Joda-Time 2.3。
DateTimeZone timeZone = DateTimeZone.forID( "America/Montreal" ); // Specify a time zone rather than rely on default.
DateTime now = DateTime.now( timeZone );
以合理的ISO 8601格式生成字符串表示形式。本标准使用24小时制。
String outputIso = now.toString();
以本地化格式生成字符串表示。
java.util.Locale locale = java.util.Locale.CANADA_FRENCH;
DateTimeFormatter formatter = DateTimeFormat.forStyle( "SS" ).withLocale( locale );
String outputQuébécois = formatter.print( now );
准确生成您指定的格式。
DateTimeFormatter formatter = DateTimeFormat.forPattern( "dd/MM/yy HH:mm" ); // See note about year in answer by Meno Hochschild.
String output = formatter.print( now );
答案 2 :(得分:1)
您需要使用SimpleDateFormat对象。
你想要的字符串是" dd / MM / YY HH:mm"
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/YY HH:mm");
Date myFormattedDate = dateFormat.parse(myUnformattedDate);
System.out.println(myFormattedDate.toString());