Reputation: 363
I have a use case to parse string to Date for different styles(short, Medium or Full) and locale(US,UK..). so I have used DateFormat.getDateInstance(style,locale) to parse the string to date, while parsing it is throwing Unparseable exception for "2015/08/14@10:00:00:GMT" except DateFormat.MEDIUM style.i want to how to parse the same string to date for DateFormat.SHORT or DateFormat.FULL style.
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
public class Testing {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
DateFormat formatter = DateFormat.getDateInstance(DateFormat.MEDIUM,Locale.US);
Date sd = formatter.parse("2015/08/14@10:00:00:GMT");
}
}
In above code if i modify DateFormat.MEDIUM to DateFormat.SHORT or DateFormat.FULL, it is not parsing the string to date.
Upvotes: 0
Views: 4529
Reputation: 153
In your code the date-pattern of formatter
differs from your date (string representation)
The pattern of DateFormat.getDateInstance(DateFormat.MEDIUM,Locale.US)
is MMM d, yyyy
and a correct conversion in code:
//pattern = MMM d, yyyy
DateFormat formatter = DateFormat.getDateInstance(DateFormat.MEDIUM,Locale.US);
Date sd_correct = formatter.parse("Aug 14, 2015");
To parse your date successfully, the correct DateFormat
instance is needed:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd'@'HH:mm:ss:z");
Date sd = dateFormat.parse("2015/08/14@10:00:00:GMT");
See Java string to date conversion for more details.
Upvotes: 2
Reputation: 1565
This is because each DateFormat default value (DateFormat.MEDIUM, DateFormat.SHORT, DateFormat.FULL) assumes some string representation, and string represeting DateFormat.MEDIUM is different from what represents DateFormat.SHORT or DateFormat.FULL..
Following tutorial should help you : DateFormat Default Values
Upvotes: 1