Parse Date from String in this format : dd/MM/yyyy [to dd/MM/yyyy]

后端 未结 4 921
死守一世寂寞
死守一世寂寞 2020-12-03 23:45

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 pre

4条回答
  •  死守一世寂寞
    2020-12-04 00:06

    Use java.text.DateFormat and java.text.SimpleDateFormat to do it.

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

    UPDATE:

    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.

提交回复
热议问题