Reputation: 69
I have the input string as 2012-07-27
and I want the output as Date
but with the same format like 2012-07-27
DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
try {
Date today = df.parse("20-12-2005 23:59:59");
System.out.println("Today = " + df.format(today));
} catch (ParseException e) {
e.printStackTrace();
}
20-12-2005 23:59:59
But it's string object I want the same output (20-12-2005 23:59:59
) as date object not as string object.
How can I get the Date
in the form DD-MM-YYYY HH:MM:SS
?
Upvotes: 1
Views: 3521
Reputation: 66657
Date today
is the date
object you get for input String
. There are nothing like formatted dates in Java. Date is always just date object. You perform all sorts of operations on that date object and when you want to Store (or) display just apply format()
df.format(today) // is just for formatting and display purpose.
Upvotes: 2
Reputation: 1028
The Date class has many deprecated methods and the only correct way to create it right now is via a long (read doc for details).
You should look into GregorialCalendar where you can pass some constant fields of Calendar as attributes.
If you want to input the date from your String, I would either do a custom parser that creates a calendar or something like this.
Hope I helped :)
Upvotes: 0
Reputation: 19185
There is difference in your format passed to SimpleDateFormat
and way you are passing date string. You should Also use HH
DateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
try {
Date today = df.parse("20-12-2005 23:59:59");
System.out.println("Today = " + df.format(today));
//To Print Real Today
System.out.println("Real Today = " + df.format(new Date()));
} catch (ParseException e) {
e.printStackTrace();
}
Upvotes: 0