Convert Java Date into another Time as Date format

2019-09-05 22:22发布

I want to convert date into "indies time". Specifically: "Asia/Calcutta".

Code:

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

Here is the output of the above code:

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

I want the DATE, not the string, but when I retrieve the date, the time is 3:10, and when I get the string, I get 15:40:04. Why are these not the same?

4条回答
走好不送
2楼-- · 2019-09-05 22:42

A Date does not contain any formatting. It is simply a Date. You can therefore not convert your Date object between different output formats. Once you have the date, there's no need trying to convert it into a different format. How to format it is decided when you convert it to a String with your SimpleDateFormat. So once you have parsed your Date, just keep it around until you need to format it for output.

查看更多
趁早两清
3楼-- · 2019-09-05 22:50

Parse will return a DateObject, so calling :

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

is somewhat similar to :

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

Remember parsing a date is just to parse a String to generate a date object, if you want to display it in a certain format, use that date object and call sdf.format on it. e.g.

 String dateStringOut=simpleDateFormat.format(d1);
 System.out.println("Output : "+dateStringOut);
查看更多
甜甜的少女心
4楼-- · 2019-09-05 22:54

parse() parses the date text and constructs the Date object which is a long value. The parse() javadoc says

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.

Your parse Date object is printed by calling the toString() on Date which has printed it in the MST timezone. If you convert it from MST to IST then you will get the timestamp which you are expecting. So, your output is correct. All you need to do is format and print your long Date value using the correct timezone.

查看更多
Luminary・发光体
5楼-- · 2019-09-05 22:58

Use static function getDateTimeInstance(int dateStyle,int timeStyle) of DateFormat class. See DateFormat Class for further details. It may help you.

查看更多
登录 后发表回答