Java将Date转换为其他格式

我有这种格式的日期字符串:

String fieldAsString = "11/26/2011 14:47:31"; 

我试图以这种格式将其转换为Date类型对象: “yyyy.MM.dd HH:mm:ss”

我尝试使用以下代码:

 SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss"); Date newFormat = sdf.parse(fieldAsString); 

但是,这会引发一个exception,即它是一个Unparsable日期。

所以我尝试过这样的事情:

 Date date = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse(fieldAsString); String newFormat = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(date) 

但是,这种新格式现在采用’String’格式,但我希望我的函数将新的格式化日期作为’Date’对象类型返回。 我该怎么办?

谢谢!

您似乎认为Date对象具有格式。 它没有。 听起来你只需要这个:

 Date date = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse(fieldAsString); 

(请注意,您应该考虑指定区域设置和可能的时区。)

然后你就得到了你的Date值。 格式仅在您以后想要将其转换为文本时才相关…那时您应该指定格式。 将所表示的值(在这种情况下是瞬间)与潜在的文本表示分开是很重要的。 它就像整数 – 这两个值之间没有区别:

 int x = 0x10; int y = 16; 

它们是相同的值,只是在源代码中表示不同。

另外考虑将Joda Time用于所有日期/时间工作 – 它比java.util.*更清晰。

Jon Skeet的回答是正确和完整的。

在java.util.Date(和下面的日期时间)的内部,日期时间值存储为自Unix 纪元以来的毫秒数。 里面没有String! 当您需要以人类可读的格式对日期时间进行文本表示时,可以调用toString或使用formatter对象来创建 String对象。 同样在解析时,输入字符串被丢弃,而不是存储在Date对象(或Joda-Time中的DateTime对象)中。

乔达时间

为了好玩,正如Skeet先生所提到的,这是与Joda-Time合作的(更好)方式。

一个主要的区别是,虽然java.util.Date类似乎有一个时区,但它没有。 相比之下,Joda-Time DateTime确实知道自己的时区。

 String input = "11/26/2011 14:47:31"; // From text to date-time. DateTimeZone timeZone = DateTimeZone.forID( "Pacific/Honolulu" ); // Time zone intended but unrecorded by the input string. DateTimeFormatter formatterInput = DateTimeFormat.forPattern( "MM/dd/yyyy HH:mm:ss" ).withZone( timeZone ); // No words in the input, so no need for a specific Locale. DateTime dateTime = formatterInput.parseDateTime( input ); // From date-time to text. DateTimeFormatter formatterOutput_MontréalEnFrançais = DateTimeFormat.forStyle( "FS" ).withLocale( java.util.Locale.CANADA_FRENCH ).withZone( DateTimeZone.forID( "America/Montreal" ) ); String output = formatterOutput_MontréalEnFrançais.print( dateTime ); 

转储到控制台……

 System.out.println( "input: " + input ); System.out.println( "dateTime: " + dateTime ); System.out.println( "dateTime as milliseconds since Unix epoch: " + dateTime.getMillis() ); System.out.println( "dateTime in UTC: " + dateTime.withZone( DateTimeZone.UTC ) ); System.out.println( "output: " + output ); 

跑的时候……

 input: 11/26/2011 14:47:31 dateTime: 2011-11-26T14:47:31.000-10:00 dateTime as milliseconds since Unix epoch: 1322354851000 dateTime in UTC: 2011-11-27T00:47:31.000Z output: samedi 26 novembre 2011 19:47 

在“joda”中搜索StackOverflow以查找更多示例。