无法在所需的SimpleDateFormat中获取日期 [英] Unable to get Date in required SimpleDateFormat

查看:0
本文介绍了无法在所需的SimpleDateFormat中获取日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  1. 2012-03-13
  2. 13:15:00-4:00
  3. 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));


    }

}

推荐答案

只需在您的格式中使用‘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}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

这篇关于无法在所需的SimpleDateFormat中获取日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆