我需要从以下日期格式获取月份短名称和日期。
给定的日期格式是:
2015-12-01 00:00:00
,我的输出日期格式是Dec, 01
。但我的代码总是返回Jan, 01
。请告诉我我的代码哪里错了。
String newdate = "";
String ip = "2015-10-01 00:00:00";
try {
String old_format = "yyyy-mm-dd HH:mm:ss";
String new_format = "MMM, dd";
SimpleDateFormat sdf = new SimpleDateFormat(old_format);
Date d = sdf.parse(ip);
SimpleDateFormat sm = new SimpleDateFormat(new_format);
newdate = sm.format(d);
System.out.println(newdate);
} catch (ParseException e) {
e.printStackTrace();
}
}
要获得预期结果,您应该使用以下格式:
String old_format = "yyyy-MM-dd HH:mm:ss";
MM
而不是 mm
来获取一年中的两位数月份
请查看http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
上的表格-> 一年中的月份M
-> 小时中的分钟m
old_format 应该是:
String old_format = "yyyy-MM-dd HH:mm:ss"; //mm -> MM
而不是做
SimpleDateFormat sm = new SimpleDateFormat(new_format);
您还可以使用 applyPattern() 方法来更改 SimpleDataFormat 的模式:
sdf.applyPattern(new_format);
newdate = sdf.format(d);
因此您不必创建另一个 SimpleDataFormat 对象。
正如其他人所说,使用:
String old_format = "yyyy-MM-dd HH:mm:ss"; //mm -> MM
如果您使用的是 Java SE 8 或更高版本(推荐),请尝试使用 java.time 类。请参阅Oracle 教程。
DateTimeFormatter oldFormatter = DateTimeFormatter.ofPattern(old_format);
DateTimeFormatter newFormatter = DateTimeFormatter.ofPattern(new_format);
LocalDateTime dateTime = LocalDateTime.parse(ip, oldFormatter);
String newdate = dateTime.format(newFormatter);
// and later optionally
MonthDay monthDay = MonthDay.parse(newdate, newFormatter);
MonthDay
你说:
获取月份短名称和日期
MonthDay
。
首先,解析您的输入字符串。该格式接近标准 ISO 8601 格式。为了符合要求,请将中间的空格替换为
T
。
String input = "2015-10-01 00:00:00".replace( " " , "T" ) ;
LocalDateTime ldt = LocalDateTime.parse( input ) ;
LocalDateTime
对象中,我们可以提取一个 MonthDay
对象。
MonthDay md = MonthDay.from( ldt ) ;
生成标准 ISO 8601 格式的文本。
md.toString()
--10-01
生成本地化文本。
Locale locale = Locale.of( "en" , "US" );
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MMMM d" ).withLocale( locale );
String output = md.format( f );
10 月 1 日