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?
A
Date
does not contain any formatting. It is simply aDate
. You can therefore not convert yourDate
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 aString
with yourSimpleDateFormat
. So once you have parsed yourDate
, just keep it around until you need to format it for output.Parse will return a DateObject, so calling :
is somewhat similar to :
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.
parse() parses the date text and constructs the Date object which is a long value. The parse() javadoc says
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.
Use static function getDateTimeInstance(int dateStyle,int timeStyle) of DateFormat class. See DateFormat Class for further details. It may help you.