I have a string in "dd-MM-yyyy HH:mm" and need to convert it to a date object in the format "yyyy-MM-dd HH:mm".
Below is the code I'm using to convert
oldScheduledDate = "16-05-2011 02:00:00";
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date oldDate = (Date)formatter.parse(oldScheduledDate);
Now when I print oldDate, i get
Sat Nov 01 02:00:00 GMT 21
, which is completely wrong, what am I doing wrong here?
String dateSample = "10-01-2010 21:10:05";
String oldFormat = "dd-MM-yyyy HH:mm:ss";
String newFormat = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat sdf1 = new SimpleDateFormat(oldFormat);
SimpleDateFormat sdf2 = new SimpleDateFormat(newFormat);
try {
System.out.println(sdf2.format(sdf1.parse(dateSample)));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
"yyyy-MM-dd" doesn't even look the same as "16-05-2011". Hmm. Well, why not?
Hints:
A simple approach is to swap around the letters.
String s = "16-05-2011 02:00:00";
String newDate=s.substring(6,10)+s.substring(3,6)+'-'+s.substring(0,2)+s.substring(10);
you need to use formatter when you want to output formatted date
public static void main(String[] args) throws ParseException {
String oldScheduledDate = "16-05-2011 02:00:00";
DateFormat oldFormatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date oldDate = (Date)oldFormatter .parse(oldScheduledDate);
System.out.println(formatter.format(oldDate));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.