将Java Date转换为另一个Time as Date格式

时间:2013-04-15 10:12:17

标签: java timezone date-conversion

我想将日期转换为“独立时间”。具体来说:“亚洲/加尔各答”。

代码:

// TODO Auto-generated method stub
Date date=new Date();
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

simpleDateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));

String dateString=simpleDateFormat.format(date);

System.out.println("Currect Date : " + dateString);
// This is returning a string and I want a date.

System.out.println("Wrong Output : "+simpleDateFormat.parse(dateString)); 
//This returns a Date but has incorrect result.

以下是上述代码的输出:

Correct Date : 2013-04-15 15:40:04
Wrong Output : Mon Apr 15 03:10:04 MST 2013

我想要DATE,而不是字符串,但是当我检索日期时,时间是3:10,当我得到字符串时,我得到15:40:04。为什么这些不一样?

4 个答案:

答案 0 :(得分:2)

parse()解析日期文本并构造Date对象,该对象是一个long值。 parse()javadoc说

The TimeZone value may be overwritten, depending on the given pattern and 
the time zone value in text. Any TimeZone value that has previously been 
set by a call to setTimeZone may need to be restored for further operations.

通过调用日期上的toString()打印您的解析日期对象,该日期已在MST时区中打印出来。如果您将其从MST转换为IST,那么您将获得您期望的时间戳。所以,你的输出是正确的。您需要做的就是使用正确的时区格式化并打印您的长日期值。

答案 1 :(得分:1)

Parse将返回一个DateObject,因此调用:

System.out.println("Wrong Output : "+simpleDateFormat.parse(dateString));

有点类似于:

Date d1 = simpleDateFormat.parse(dateString);
System.out.println("Wrong Output : "+d1.toString());

记住解析日期只是解析一个String来生成一个日期对象,如果你想以某种格式显示它,请使用该日期对象并在其上调用sdf.format。 e.g。

 String dateStringOut=simpleDateFormat.format(d1);
 System.out.println("Output : "+dateStringOut);

答案 2 :(得分:1)

Date不包含任何格式。它只是一个Date。因此,您无法在不同的输出格式之间转换Date对象。获得日期后,无需尝试将其转换为其他格式。当您使用String将其转换为SimpleDateFormat时,决定如何格式化。因此,一旦解析了Date,只需将其保留,直到需要将其格式化为输出。

答案 3 :(得分:0)

使用DateFormat类的静态函数getDateTimeInstance(int dateStyle,int timeStyle)。 有关更多详细信息,请参阅DateFormat类。它可能对你有帮助。

相关问题