0

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

代码:

// 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

4 回答 4

2

parse() 解析日期文本并构造一个长值的 Date 对象。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.

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

于 2013-04-15T10:29:37.077 回答
1

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

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

有点类似于:

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

请记住,解析日期只是解析字符串以生成日期对象,如果要以某种格式显示它,请使用该日期对象并在其上调用 sdf.format 。例如

 String dateStringOut=simpleDateFormat.format(d1);
 System.out.println("Output : "+dateStringOut);
于 2013-04-15T10:18:47.917 回答
1

ADate不包含任何格式。它只是一个Date. 因此,您不能Date在不同的输出格式之间转换您的对象。一旦有了日期,就无需尝试将其转换为不同的格式。当你String用你的SimpleDateFormat. 所以一旦你解析了你Date的 .

于 2013-04-15T10:18:56.060 回答
0

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

于 2013-04-15T10:22:25.667 回答