繁体   English   中英

如何在不知道字符串格式的情况下将字符串转换为日期?

[英]How to Convert String to Date without knowing the format of String?

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

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

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

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

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

不管获得的格式如何,我都需要将其转换为所需的格式。 如何实现呢?

我在那儿没看到片段

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);

仅当我们知道解析String的输入格式时,以上代码段才有效。 但是就我而言,我不知道输入格式。 所以我在想直接使用格式格式而不进行分析。

这可能吗?

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

如您所说,日期将是例如: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();
        }

谢谢大家的所有评论和答复。

即使是我,也无法在不知道其输入格式的情况下将String转换为Date。 无论如何,我将尝试对设计进行修改以更改读取输入的方式。

再次感谢。

这取决于设计。

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.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM