【问题标题】:How to Convert String to Date without knowing the format of String?如何在不知道字符串格式的情况下将字符串转换为日期?
【发布时间】:2013-09-24 10:57:59
【问题描述】:

在我的应用程序中,我正在以字符串格式从用户读取 date 参数。

读取参数后,需要将String转换为*想要的日期格式.*

所需格式 = YYYY-MM-DD HH:MM:SS

输入字符串可以是任何格式。

例如:2013/09/19 14:21:07 2013-09-19 14:21:07

无论获得何种格式,我都需要将其转换为所需的格式。 如何做到这一点?

我看到几个sn-p在哪里,

SimpleDateFormat formatter = new SimpleDateFormat("YYYY/MM/DD HH:MM:SS"); 
Date dt = formatter.parse("2013/09/19 14:21:07");
SimpleDateFormat desiredFormatter = new
SimpleDateFormat("YYYY-MM-DD HH:MM:SS");

desiredFormatter .format(dt);

上面的 sn-p 只有在我们知道解析字符串的输入格式时才有效。 但就我而言,我不知道输入格式。所以我想直接使用 format 方法而不进行解析。

这可能吗?

【问题讨论】:

  • 你从哪里得到输入字符串,你不知道格式?在这种情况下,我们真的无能为力。
  • 转换任何您不知道其格式的数据的方式相同。用魔法。
  • 输入字符串可以是任何格式吗?你怎么知道2013/08/05 是指 2013 年 8 月 5 日还是 2013 年 5 月 8 日?
  • 做不到,你可能能够支持多种已知格式,但是你不能解析未知格式的东西。即使有多种已知格式,您也需要确保没有歧义,或者以对您的应用程序有意义的方式处理歧义。 (也许如果有多种格式匹配,您可以给用户一个选择,或者仅在一种格式匹配时接受,或者按优先顺序接受...

标签: java date


【解决方案1】:

这是不可能的。如果您事先不知道真实格式,则无法确定 01/01/2013 是 MM/dd/yyyy 还是 dd/MM/yyyy

【讨论】:

    【解决方案2】:

    如您所说,日期将是 例如:2013/09/19 14:21:07 或 2013-09-19 14:21:07

    我认为这种方式对你有用

    String text="date in yyy/mm/dd or yyy-mm-dd"
    SimpleDateFormat sdf1=null;
            try {
                if(text.contains("/"))
                {
                   sdf1  = new SimpleDateFormat("yyyy/MM/dd");
    
                }
                else
                {
                   sdf1  = new SimpleDateFormat("yyyy-MM-dd");
    
                }
                SimpleDateFormat sdf2 = new SimpleDateFormat("MMM dd yyyy");
    
                Date date = sdf1.parse(text);
    
                System.out.println("Result==> " + sdf2.format(date));
            } catch (ParseException exp) {
                exp.printStackTrace();
            }
    

    【讨论】:

      【解决方案3】:

      谢谢各位, 对于您的所有评论和答案。

      我什至觉得在不知道其输入格式的情况下无法将String转换为Date。 无论如何,我会尝试重新设计以改变读取输入的方式。

      再次感谢。

      【讨论】:

        【解决方案4】:

        这取决于设计。

        1. If user can type any format in GUI side, then we can't able to convert, simply its impossible.
        2. If user date format is validated with any specific format in GUI, then we can able to convert it With extra condition in server side coding.
        

        【讨论】:

          猜你喜欢
          • 2011-04-12
          • 2011-12-29
          • 1970-01-01
          • 1970-01-01
          • 2018-08-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-11-10
          相关资源
          最近更新 更多