以这种格式从字符串解析日期:dd / MM / yyyy [to dd / MM / yyyy] [英] Parse Date from String in this format : dd/MM/yyyy [to dd/MM/yyyy]

查看:189
本文介绍了以这种格式从字符串解析日期:dd / MM / yyyy [to dd / MM / yyyy]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为Java中用这种格式解析字符串的最佳方式是
dd / MM / yyyy [到dd / MM / yyyy]。带[]的字符串是可选的,dd代表日期的2位数表示,MM是月份的2位数表示,yyyy是年份的4位数表示。

I thinking what is the best way in Java to parse the String with this format dd/MM/yyyy [to dd/MM/yyyy]. The string with the [] are optional and dd stand for the 2 digit presentation of dates, MM is the 2 digit presentation of month and yyyy is the 4 digit presentation of year.

更新

感谢大家的快速反应,不过我忘了告诉你[]是符号可选,字符串中没有[]示例字符串可能是

Thanks guys for the fast response, however I forgot to tell you the [] is to symbolize optional, there is no [] in the string a sample String might be


  • 22 / 01/2010

  • 22/01/2010至23/01/2010

  • null

当前我用这种方式编写代码,工作但很难看=(

Current I wrote the code this way, work but is ugly =(

String _daterange = (String) request.getParameter("daterange");
    Date startDate = null, endDate = null;
    // Format of incoming dateRange is 
    if (InputValidator.requiredValidator(_daterange)) {
        String[] _dateRanges = _daterange.toUpperCase().split("TO");
        try {
            startDate = (_dateRanges.length > 0) ? sdf.parse(_dateRanges[0]) : null;
            try{
                endDate = (_dateRanges.length > 1) ? sdf.parse(_dateRanges[1]) : null;
            }catch(Exception e){
                endDate = null;
            }
        } catch (Exception e) {
            startDate = null;
        }
    }


推荐答案

使用 java.text.DateFormat java.text.SimpleDateFormat 来做。

DateFormat sourceFormat = new SimpleDateFormat("dd/MM/yyyy");
String dateAsString = "25/12/2010";
Date date = sourceFormat.parse(dateAsString);

更新:

如果你有两个隐藏在该String中的日期,您必须将它们分成两部分。我认为其他人已经指出了分裂的想法。我只是在空白处打破并扔掉TO。

If you have two Dates hiding in that String, you'll have to break them into two parts. I think others have pointed out the "split" idea. I'd just break at whitespace and throw the "TO" away.

不要担心效率。你的应用程序很可能充满了比这更糟糕的低效率。只有在分析告诉你这个片段是最糟糕的罪犯时才能正常工作并重构它。

Don't worry about efficiency. Your app is likely to be riddled with inefficiencies much worse than this. Make it work correctly and refactor it only if profiling tells you that this snippet is the worst offender.

这篇关于以这种格式从字符串解析日期:dd / MM / yyyy [to dd / MM / yyyy]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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