0

I have the String 201510251010 that represents the date 2015/10/25 10:10. I want obtain the date as String with the second format.

I have this code:

 String myString = "201510151235";
 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmm");
 SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
 Date d = dateFormat.parse(myString);
 String s = dateFormat2.format(d);

It works but I think this is ugly code. Is there a way to do the same with regex and replaceAll or something similar?

3
  • 1
    I second @stribizhev opinion, it looks more elegant and concise than using regex. Commented Aug 10, 2015 at 12:13
  • 1
    Yes. Me, too. The only thing which could improve readability in this very case is inlining and/or renaming some variables. Commented Aug 10, 2015 at 12:14
  • 1
    Regex are powerful, but they are a hassle for most developers when it comes to maintenance or readability (even to those who wrote them in the first place). I love them, yet use them only when I really have a case to support it. Always remember: the next developer on your project is a psychopath and he knows where you live. Commented Aug 10, 2015 at 12:28

2 Answers 2

2

You could try with

String myString = "201510151235";
String formatted = myString.replaceAll("(\\d{4})(\\d{2})(\\d{2})(\\d{2})(\\d{2})", 
                                       "$1-$2-$3 $4:$5");
                                  //or "$1/$2/$3 $4:$5"); 

but I doubt it looks more readable than what you have, and it certainly isn't as safe as SimpleDateFormat.

Sign up to request clarification or add additional context in comments.

3 Comments

@Chop True, but requirement is not clear since in question OP used 2015/10/25 10:10 but in code we can find "yyyy-MM-dd HH:mm", So since I was trying to rewrite code I picked version from code :)
I missed that detail. Nice catch and good choice: when the code and doc don't agree, the code is right. ;)
Thank you. It works properly. Although, keeping in mind your advices, I will use DateFormat.
2

AFAIK, for dates, parsing them with date time object is a good choice rather than regexes, since with this way you can support different culture dates as well, otherwise for different cultures, pattern may vary. So, yours way looks good to me.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.