将字符串转换为日期格式。

4

我希望的格式是 2012年12月6日 12:10

  String time = "2012-12-08 13:39:57 +0000 ";

  DateFormat sdf = new SimpleDateFormat("hh:mm:ss");
  Date date = sdf.parse(time);

  System.out.println("Time: " + date);

感谢大家的回复。 - Ketan Ahir
5个回答

8
你需要首先解析你的日期字符串(使用 DateFormat#parse() 方法)以获取与 date string 格式匹配的Date 对象。
然后,使用所需的格式在 SimpleDateFormat 中格式化该日期对象(使用 DateFormat#format() 方法)以获取字符串。
String time = "2012-12-08 13:39:57 +0000";

Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z").parse(time);
String str = new SimpleDateFormat("dd MMM yyyy HH:mm:ss").format(date);

System.out.println(str);

输出:-

08 Dec 2012 19:09:57

在第一种格式中,Z 用于匹配您的日期字符串中的 +0000,以符合 RFC 822 TimeZone。有关在日期格式中使用的其他选项,请参见 SimpleDateFormat

我在日志中找到了这个... java.lang.IllegalArgumentException: 未知的模式字符 - 'X' - Ketan Ahir
@kettu.. 在我的情况下它是有效的。无论如何,尝试使用 Z 而不是 X"yyyy-MM-dd HH:mm:ssZ" - Rohit Jain
用这个得到了答案... date = new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(time1); String str = new SimpleDateFormat("dd MMM yyyy HH:mm").format(date); 非常感谢。 - Ketan Ahir
@kettu.. 哦!你只需要到 mm 吗?是的,我刚在问题中注意到了。无论如何,很高兴你得到了它。不用谢 :) - Rohit Jain

4

SimpleDateFormat更改为:

String time = "2012-12-08 13:39:57 +0000";
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");
Date date = sdf.parse(time);
DateFormat sdf = new SimpleDateFormat("dd MMM yyyy HH:mm:ss");
String formatedTime = sdf.format(date);
System.out.println("Time: " + formatedTime);

我知道这个,但是我遇到了无法解析的字符串异常。 - Ketan Ahir

3

请看SimpleDateFormat。代码大致如下:

SimpleDateFormat fromUser = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd");

String reformattedStr = myFormat.format(fromUser.parse(inputString));

1
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("dd-MM-yyyy");
Date date=simpleDateFormat.parse("23-09-2008");

1
你可以使用SimpleDateFormat类来做这件事,如下所示:
DateFormat mydate1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date1 = mydate1.parse(time);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接