Reputation: 21893
I have this code to convert a string to a date. but the resulting date is always in another format.
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm");
try {
String dateString = "18/01/2013 11:59";
dateTest = format.parse(dateString);
System.out.println(dateTest); //output: Tue Jan 18 11:59:00 GMT 2013
}
How can I make it so that dateTest
is in the same format as the original?
Upvotes: 0
Views: 76
Reputation: 11
Both java.util.Date and java.sql.Date store seconds and year, that's why you're seeing them when you print dateTest. If you want print the date in the format you provided (dd/MM/yyyy HH:mm) you simply need to format the date.
Date dateTest;
SimpleDateFormat desiredDateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm");
try
{
String dateString = "18/01/2013 11:59";
dateTest = desiredDateFormat.parse(dateString);
System.out.println(desiredDateFormat.format(dateTest)); //output: 18/01/2013 11:59
}
catch (Exception ex)
{
//do something
}
Upvotes: 1
Reputation: 37823
This
System.out.println(format.format(dateTest));
will do the job. You can use the format()
method of your SimpleDateFormat
to format the output the same way your input should be.
Upvotes: 2
Reputation: 17445
You can't, because a Date does not have a 'format'.
If you need this, you could create your own Date class that contains a built-in format, but it'd be icky.
The normal way is to format the date as you print it.
System.out.println(format.format(dateTest));
Upvotes: 1
Reputation: 6089
Format the date using the same SimpleDateFormat you used to parse it.
Upvotes: 3