Java日期格式允许 - /或.作为日期内的分隔符

Tar*_*ski 5 java date-format simpledateformat

解析可以采用以下格式之一的日期的最佳方法是什么

 "dd-MM-yyyy HH:mm"
 "dd/MM/yyyy HH:mm"
 "dd.MM.yyyy HH:mm"
Run Code Online (Sandbox Code Playgroud)

不创建3个SimpleDateFormats并解析每个.

谢谢

kgi*_*kis 5

你可以先运行两个替换操作,以便将所有三种格式减少到一个吗?


Jon*_*eet 5

将源字符串"调整"为规范格式可能最简单:

if (text.length() == 16)
{
    if ((text.charAt(2) == '/' && text.charAt(5) == '/') ||
        (text.charAt(2) == '.' && text.charAt(5) == '.'))
    {
        text = text.substring(0, 2) + "-" + text.substring(3, 5) 
           + "-" + text.substring(6);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后使用" - "格式字符串.

请注意,这是非常具体的,只有更换正是你感兴趣的人物,以避免不必要的副作用.