Reputation: 618
I have the following:
String[] string_dates = new String[10]
// read in strings formatted via fmt1 dd-MMM-yy)
Date[] date_dates = new Date[10];
for (int i = 0; i < 9; i++){
date_dates[i] = fmt1.parse(string_dates[i]);
What would be the most efficient way to format the Dates in date_dates[] to format dd-MM-yyyy? Should I convert the Strings in strings_dates[] to format dd-MM-yyyy first, and then read them into dates? Thank you.
Upvotes: 1
Views: 4842
Reputation: 347184
A Date
is the representation of the number of milliseconds since the Unix epoch. It has no concept of a format of it's own (other then that created by toString
, which should not worry about)...
Once you have converted the String
representation of the date to a Date
, you should then use an appropriate formatter to format that date in what ever format you want...
String[] stringDates = {
"01-MAR-2013",
"02-MAR-2013",
"03-MAR-2013",
"04-MAR-2013",
"05-MAR-2013",
"06-MAR-2013",
"07-MAR-2013",
"08-MAR-2013",
"09-MAR-2013",
"10-MAR-2013"};
SimpleDateFormat inFormat = new SimpleDateFormat("dd-MMM-yyyy");
Date[] dates = new Date[stringDates.length];
for (int i = 0; i < stringDates.length; i++) {
try {
dates[i] = inFormat.parse(stringDates[i]);
} catch (ParseException ex) {
ex.printStackTrace();
}
}
SimpleDateFormat outFormat = new SimpleDateFormat("dd-MM-yyyy");
for (Date date : dates) {
System.out.println("[" + date + "] - [" + outFormat.format(date) + "]");
}
Which produces...
[Fri Mar 01 00:00:00 EST 2013] - [01-03-2013]
[Sat Mar 02 00:00:00 EST 2013] - [02-03-2013]
[Sun Mar 03 00:00:00 EST 2013] - [03-03-2013]
[Mon Mar 04 00:00:00 EST 2013] - [04-03-2013]
[Tue Mar 05 00:00:00 EST 2013] - [05-03-2013]
[Wed Mar 06 00:00:00 EST 2013] - [06-03-2013]
[Thu Mar 07 00:00:00 EST 2013] - [07-03-2013]
[Fri Mar 08 00:00:00 EST 2013] - [08-03-2013]
[Sat Mar 09 00:00:00 EST 2013] - [09-03-2013]
[Sun Mar 10 00:00:00 EST 2013] - [10-03-2013]
You should avoid the temptation to save the formatted Date
and instead simply keep the Date
object and format it as you need.
Upvotes: 2
Reputation: 4766
you can format the string in to date type using following SimpledateFormat in java. Following is the example
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
String dateInString = "7-Jun-2013";
try {
Date date = formatter.parse(dateInString);
System.out.println(date);
System.out.println(formatter.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
Note For complete date and time patterns, please refer to this java.text.SimpleDateFormat JavaDoc.
Well in you case please take a look at these resourcesclick here
You can give "dd-MM-yyy". Please try it
Upvotes: 2