Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Not able parse the Date  RSS feed

 
srikanth darbha
Ranch Hand
Posts: 55
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Code ranch,

Can anyone please help me out ,

I have the below piece of code ,

import java.util.*;
import java.text.SimpleDateFormat;


public class test
{
public static void main(String [] args) throws Exception
{
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String dateInString = "2016-11-27 00:00:00.0";
Date date = formatter.parse(dateInString);
System.out.println(date);

}

}
}

I am trying to convert the above dateInstring to yyyy-MM-dd format (2016-11-27) ,but on running it i am getting the output as

Sun Nov 27 00:00:00 UTC 2016

Can you please help me out in this!!

Thanks in Advance..
 
Dave Tolls
Rancher
Posts: 2909
35
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Date objects do not have a format.
When you print a Date object it uses whatever the default Locale date format happens to be.

If you want to print a Date in a specific format then you need to use the SimpleDateFormat to format it.

This gives "2016-02-19" as the output.
 
Winston Gutkowski
Bartender
Posts: 10573
65
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
srikanth darbha wrote:I am trying to convert the above dateInstring to yyyy-MM-dd format (2016-11-27)

Then why not just drop the last bit? ie:
  System.out.println(dateInstring.substring(0, dateInstring.indexOf(' '));
?

The fact is that your parse method IS dropping the time, as you would have discovered if you'd written:
  String dateInString = "2016-11-27 12:34:56.7";
because this would STILL have produced:
  Sun Nov 27 00:00:00 UTC 2016

So, you need to decide (and explain to us) WHAT you want to do:
1. Do you simply want to change a date/time String to a date String?
2. Do you want to convert a date/time String to a Date without a time?
(because that's what you've done)
3. Do you want to convert a Date to a String without a time?

Because all three conversions are different.

HIH

Winston
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!