无法在所需的SimpleDateFormat中获取日期所需、日期、SimpleDateFormat

由网友(莫离莫弃〆)分享简介:下面是简单日期格式的My代码。我在哪里得到O/P2012-03-1313:15:00-4:002012/03/13 13:15:00 +0530但我需要MM/dd/yyyy HH:mm格式的O/Ppublic class Time {public static void main(String args[]) th...

下面是简单日期格式的My代码。我在哪里得到O/P

2012-03-13 13:15:00-4:00 2012/03/13 13:15:00 +0530

但我需要MM/dd/yyyy HH:mm

格式的O/P
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));


    }

}

推荐答案

208 SimpleDateFormat

只需在您的格式中使用‘T’文字,然后SimpleDateFormat将为您执行解析。这是一个在Java 6中工作的解决方案,它处理-4.00,它的工作方式是分离行尾的垃圾数据,并要求时区对其进行转换,然后在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}Td{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
阅读全文

相关推荐

最新文章