如何在java中格式化日期?

如何将此日期格式“2011-09-07T00:00:00 + 02:00”更改为“dd.MM”。 即“07.09。”

提前致谢!

这是一个样本

编辑了代码:

public static void main(String[] args) throws ParseException { String input = "2011-09-07T00:00:00+02:00"; SimpleDateFormat inputDf = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat outputDf = new SimpleDateFormat("dd.MM"); Date date = inputDf.parse(input.substring(0,9)); System.out.println(date); System.out.println(outputDf.format(date)); } 

基本上 –

  1. 从上面的字符串创建日期格式对象

  2. 解析为日期对象,然后根据您的喜好重新格式化。

例如(我没有测试过这个):

 /* * REFERENCE: * http://javatechniques.com/blog/dateformat-and-simpledateformat-examples/ */ import java.text.DateFormat; import java.util.Date; public class DateFormatExample1 { public static void main(String[] args) { // Make a new Date object. It will be initialized to the current time. DateFormat dfm = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss"); Date d = dfm.parse("2011-09-07 00:00:00"); // See what toString() returns System.out.println(" 1. " + d.toString()); // Next, try the default DateFormat System.out.println(" 2. " + DateFormat.getInstance().format(d)); // And the default time and date-time DateFormats System.out.println(" 3. " + DateFormat.getTimeInstance().format(d)); System.out.println(" 4. " + DateFormat.getDateTimeInstance().format(d)); // Next, try the short, medium and long variants of the // default time format System.out.println(" 5. " + DateFormat.getTimeInstance(DateFormat.SHORT).format(d)); System.out.println(" 6. " + DateFormat.getTimeInstance(DateFormat.MEDIUM).format(d)); System.out.println(" 7. " + DateFormat.getTimeInstance(DateFormat.LONG).format(d)); // For the default date-time format, the length of both the // date and time elements can be specified. Here are some examples: System.out.println(" 8. " + DateFormat.getDateTimeInstance( DateFormat.SHORT, DateFormat.SHORT).format(d)); System.out.println(" 9. " + DateFormat.getDateTimeInstance( DateFormat.MEDIUM, DateFormat.SHORT).format(d)); System.out.println("10. " + DateFormat.getDateTimeInstance( DateFormat.LONG, DateFormat.LONG).format(d)); } } 

您的代码需要对以下行进行一些修正

 Date date = inputDf.parse(input.substring(0,9)); 

代替(0,9)你需要输入(0,10) ,你将获得所需的输出。

TL;博士

 OffsetDateTime.parse( "2011-09-07T00:00:00+02:00" ).format( DateTimeFormatter.ofPattern( "dd.MM" ) 

java.time

问题和其他答案使用旧的遗留类,这些类已被certificate是麻烦和混乱的。 它们已被java.time类取代。

您的输入字符串采用标准ISO 8601格式。 默认情况下,这些格式在java.time类中使用。 因此无需指定格式化模式。

 OffsetDateTime odt = OffsetDateTime.parse( "2011-09-07T00:00:00+02:00" ); 

您可以生成所需格式的字符串。

 DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd.MM" ); String output = odt.format( f ); 

MonthDay

你想要月和日。 实际上有一个类, MonthDay

 MonthDay md = MonthDay.from( odt ); 

您可以生成所需格式的字符串。

 DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd.MM" ); String output = md.format( f );