问题
Below is the my code for Simple date format.Where iam getting o/p as
2012-03-13
13:15:00-4:00
2012/03/13 13:15:00 +0530
but i need the o/p in the format MM/dd/yyyy HH:mm
public class Time {
public static void main(String args[]) throws ParseException
{
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat ti=new SimpleDateFormat("MM/dd/yyyy HH:mm");
SimpleDateFormat sdf1=new SimpleDateFormat("yyyy/MM/dd HH:mm:ss Z");
String dt= "2012-03-13T13:15:00-4:00";
String st[]=dt.split("T");
System.out.println(st[0]);
System.out.println(st[1]);
String time[]= st[1].split("-");
Date fromDt =(Date)sdf.parse(st[0]+" "+time[0]);
System.out.println(sdf1.format(fromDt));
}
}
回答1:
Not sure I understand properly, but it seems your last line should be:
System.out.println(ti.format(fromDt)); //prints 03/13/2012 13:15
If your input were properly formatted (note the -04:00
instead of -4:00
in dt), you could just do this:
SimpleDateFormat input = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
SimpleDateFormat output = new SimpleDateFormat("MM/dd/yyyy HH:mm");
String dt = "2012-03-13T13:15:00-04:00";
Date date = input.parse(dt);
System.out.println(output.format(date)); //prints 03/13/2012 17:15 with my local timezone
output.setTimeZone(TimeZone.getTimeZone("GMT-08:00"));
System.out.println(output.format(date)); //prints 03/13/2012 09:15
Note: XXX
has been introduced in Java 7 so would not work with an earlier version of the JDK.
回答2:
Just use a 'T' literal in your format, then SimpleDateFormat will do the parsing for you. Here's a solution that works in java 6, and deals with -4.00, it works by separating out the junk at the end of the line and asking TimeZone to convert it, that timeZone is then used on the SimpleDateFormat.
SimpleDateFormat input = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
SimpleDateFormat output = new SimpleDateFormat("MM/dd/yyyy HH:mm");
String dt = "2012-03-13T13:15:00 -4:00";
Pattern pattern = Pattern
.compile("\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\s*(.*)");
Matcher m = pattern.matcher(dt);
if (m.find()) {
String zoneJunk = m.group(1);
TimeZone zone = TimeZone.getTimeZone("GMT" + zoneJunk);
input.setTimeZone(zone);
}
Date date = input.parse(dt);
System.out.println(output.format(date)); // prints 03/13/2012 17:15
来源:https://stackoverflow.com/questions/9683957/unable-to-get-date-in-required-simpledateformat