
Nearly any project that amounts to anything must handle the processing of Dates, Times, and Timestamps. When it comes to Java projects, I see time and time again that developers just insert date formatters anywhere and everywhere. This violates the concept of modularity and making a segment of code do one thing and it do it well. Furthermore, this leads to lots of copy and paste duplicate code, which in turn leads to less testable code. Ultimately, this degrades internal code quality for a project. Moreover, and perhaps most importantly, I feel many developers fail to understand how flawed and poor the standard Java date and time classes are, which predate Java 8 (see here for starters). Lastly, I also see many different date formats used in code bases. It is my opinion, that internally in Java code, only one date format should be used and it should be the ISO8601 standard format: yyyy-dddTHH:MM:SS.SSS
. Even better, would be utilize time zone information in UTC/Zulu. This format easily and readably demarcates the date from the time, it is sortable in chronological order, and eliminates the guessing game that sometimes accompanies ready a timestamp.
As a result, I will be showing you a way to write a single utility method for parsing dates represented as Strings, in multiple formats, into java.util.Date
objects. This will be done with one of the most respected date and time libraries out there: Joda Time. Joda is the defacto standard, in my opinion, for date and time manipulations prior to Java 8. Also, I will show you a JUnit Theory test to exercise the utility method I created. So, here it is
import java.util.Date;
import org.joda.time.LocalDateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.DateTimeFormatterBuilder;
public class TimeUtil {
private DateTimeFormatter formatter = null;
/**
* Utility that can convert several different formatted strings into
* {@link Date} like
* <ul>
* <li>yyyyMMdd
* <li>yyyy-MM-dd
* <li>MM/dd/yyyy
* </ul>
*
* @param strDate
* @return
*/
public Date stringAsDate(String strDate) {
if (strDate == null || strDate.isEmpty()) {
return null;
}
else {
try {
if (formatter == null) {
formatter = new DateTimeFormatterBuilder().appendOptional(DateTimeFormat.forPattern("yyyyMMdd")
.getParser())
.appendOptional(DateTimeFormat.forPattern("yyyy-MM-dd")
.getParser())
.appendOptional(DateTimeFormat.forPattern("MM/dd/yyyy")
.getParser())
.toFormatter();
}
LocalDateTime dateTime = LocalDateTime.parse(strDate, formatter);
return dateTime.toDate();
}
catch (Exception e) {
return null;
}
}
}
}
Now, here we can we have a utility method, which supports three different date formats. It also efficiently only builds the formatter once. Lastly, it is easily extendable to more formats if needed, but again, it should be best practice to minimize or normalize the formats used throughout a project.
Next, here is a simple JUnit Theory test, which takes multiple date Strings and all of which pass the Theory test.
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertThat;
import java.util.Date;
import org.joda.time.LocalDate;
import org.junit.experimental.theories.DataPoints;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.runner.RunWith;
@RunWith(Theories.class)
public class TimeUtilTheoryTest {
private TimeUtil timeUtil = new TimeUtil();
@DataPoints
public static String[] strDates = new String[] { "20180429", "2018-04-29", "04/29/2018", "01/20/1999", "1899-12-25",
"2020-02-29", // leap year future
"00010101", "19160229" // leap year past
};
@Theory
public void testStringAsDate(String strDate) {
Date date = timeUtil.stringAsDate(strDate);
assertThat(date, is(not(nullValue())));
String year = null;
String month = null;
String day = null;
if (strDate.contains("-")) {
String[] parts = strDate.split("-");
year = parts[0];
month = parts[1];
day = parts[2];
}
else if (strDate.contains("/")) {
String[] parts = strDate.split("/");
year = parts[2];
month = parts[0];
day = parts[1];
}
else {
year = strDate.substring(0, 4);
month = strDate.substring(4, 6);
day = strDate.substring(6);
}
LocalDate ld = new LocalDate(Integer.valueOf(year), Integer.valueOf(month), Integer.valueOf(day));
assertThat(date, is(ld.toDate()));
}
}
Here we can see we have an array of DataPoints. Each item in the array is passed to the Theory to be tested, one after the other. If all of the given DataPoints are successfully executed against the Theory, then the Unit test passes. This prevent you from writing the same or similar unit test over and over. Even so, I do find Theories a little limited when you want to mix positive and negative DataPoints. You either need to filter out bad data with Assumptions or Assertions. Or, alternatively, you could create a more complex object for your array of DataPoints with the expected answers or flags to guide your tests.
Hopefully this has helped you learn how to effectively and concisely parse formatted strings into java.util.Date
objects. Remember, this was done with third party Java API known as Joda Time, which is considered a superior date and time library for versions of Java predating version 8. In fact, you will notice in Java 8 that much of Joda seems to have been borrowed and integrated into the core of Java 8 with JSR-310. Also, I hope this post gives you a taste of the power of JUnit Theories as opposed to the tradition JUnit test.
Can I just say what a relief to seek out somebody who truly knows what theyre speaking about on the internet. You undoubtedly know how one can convey an issue to mild and make it important. More folks have to read this and perceive this aspect of the story. I cant believe youre no more well-liked since you definitely have the gift.
i would really love to play card games, it is also a very addictive game*
It arduous to search out educated people on this topic, but you sound like you realize what you are talking about! Thanks
hi, I’ve been gettin my site ranked “big affiliate profits”.
Nice post. I was checking continuously this blog and I am impressed! Very helpful information specially the last part I care for such information a lot. I was looking for this certain information for a very long time. Thank you and best of luck.
i always admire PETA, they really protect some of the helpless animals on this planet::
The next occasion Someone said a blog, Lets hope it doesnt disappoint me as much as this place. I am talking about, I know it was my method to read, but I actually thought youd have some thing fascinating to say. All I hear is actually a few whining about something that you could fix if you werent too busy interested in attention.
That is the right weblog for anyone who wants to find out about this topic. You understand so much its almost laborious to argue with you (not that I truly would want…HaHa). You definitely put a brand new spin on a subject thats been written about for years. Great stuff, just nice!
It¡¦s in reality a great and useful piece of information. I¡¦m glad that you simply shared this useful info with us. Please stay us up to date like this. Thank you for sharing. rent a car pristina
Wonderful paintings! This is the kind of info that are meant to be shared across the net. Disgrace on search engines for no longer positioning this publish upper! Come on over and talk over with my website . Thank you =)
That is a really amazing powerful resource that you’re offering and you just provide it away cost-free!! I that can compare with discovering websites which comprehend the particular valuation on providing you with fantastic learning resource for zero cost. We truly dearly loved examining this web site. Have fun here!
I’m impressed, I must say. Very rarely do I come across a blog that’s both informative and entertaining, and let me tell you, you’ve right from the beginning. Your blog is important, the issue is something that not enough people are talking intelligently about.
Hello there, just became alert to your blog through Google, and found that it’s truly informative. I am going to watch out for brussels. I will appreciate if you continue this in future. A lot of people will be benefited from your writing. Cheers!
Hello there, I discovered your site by way of Google whilst searching for a related topic, your website came up, it seems to be good. I’ve bookmarked it in my google bookmarks.
It’s quite hard to find a good site. And I think I am lucky enough to have come here. The posts are doing great and full of good insights. I would be glad to keep on coming back here to check for updates!
Its like you read my mind! You seem to know so much about this, like you wrote the book in it or something. I think that you could do with a few pics to drive the message home a little bit, but instead of that, this is excellent blog. A fantastic read. I’ll definitely be back.
I was also reading a topic like this one from another site.’”‘”*
I wanted to compose you the little observation just to thank you once again regarding the exceptional basics you have shared on this site. It has been simply wonderfully open-handed of people like you to supply publicly just what a few people would have sold for an electronic book to help with making some bucks for their own end, mostly now that you could possibly have tried it if you decided. These thoughts likewise acted as the fantastic way to be aware that the rest have the identical desire really like mine to figure out somewhat more with regards to this issue. Certainly there are numerous more enjoyable sessions up front for individuals that start reading your blog
the best addition on our garden that we have are those garden swings, the garden swings made our kids very very happy::
very nice post, i definitely enjoy this fabulous website, persist with it
An interesting discussion will probably be worth comment. I’m sure that you ought to write much more about this topic, may possibly not become a taboo subject but usually everyone is not enough to communicate on such topics. To the next. Cheers
You have noted very interesting details ! ps nice site.
Good – I should definitely pronounce, impressed with your web site. I had no trouble navigating through all the tabs as well as related information ended up being truly easy to do to access. I recently found what I hoped for before you know it at all. Reasonably unusual. Is likely to appreciate it for those who add forums or something, web site theme . a tones way for your client to communicate. Nice task.
paper roll… keep up your informative writing! At least i have something to look forward too when iam at work!…
You could certainly see your expertise in the paintings you write. The arena hopes for even more passionate writers such as you who are not afraid to say how they believe. All the time go after your heart.
when we are looking for apartment for rents, we usually choose those with very clean rooms,,
I’m impressed, I must say. Genuinely rarely can i encounter a blog that’s both educative and entertaining, and without a doubt, you have hit the nail on the head. Your concept is outstanding; the issue is something that too little individuals are speaking intelligently about. My business is very happy i always stumbled across this during my try to find something regarding this.
There a few fascinating points with time in this article but I do not determine if I see they all center to heart. There exists some validity but Let me take hold opinion until I investigate it further. Very good article , thanks so we want far more! Included in FeedBurner too
JDbwPuTCI
I would like to use the chance of thanking you for your professional instruction I have continually enjoyed viewing your site. I am looking forward to the particular commencement of my university research and the overall preparation would never have been complete without visiting your website. If I could be of any assistance to others
You completed some nice points there. I did a search on the topic and found mainly people will have the same opinion with your blog.
I like what you guys are up too. Such intelligent work and reporting! Carry on the excellent works guys I have incorporated you guys to my blogroll. I think it will improve the value of my web site
I like this web blog very much so much great information. “It’s a poor sort of memory that only works backward.” by Lewis Carroll.
Perfect piece of work you have done, this web site is really cool with great info .
An intriguing discussion may be valued at comment. There’s no doubt that that you ought to write much more about this topic, it will not be described as a taboo subject but usually folks are too little to chat on such topics. To a higher. Cheers
hmmm, i would love to browse mobile websites from now on, **
You produced some decent points there. I looked on the web for the issue and discovered most individuals goes as well as with your website.
You have the absolute coolest physics blog ever. The only thing is, I don’t understand the high level of physics this is talkinga about. I find it fascinating though.
As a Newbie, I am always searching online for articles that can help me. Thank you
Hello there, I found your blog via Google even as searching for a comparable matter, your web site got here up, it appears great. I have bookmarked it in my google bookmarks.
There’s noticeably a bundle to learn about this. I assume you made certain nice points in features also.
Unfortunately at some parts it becomes a little too off subject, such as how they guys change their minds on and off.
I have been exploring for a little bit for any high-quality articles or blog posts in this kind of space . Exploring in Yahoo I ultimately stumbled upon this site. Reading this information So i’m satisfied to show that I’ve a very just right uncanny feeling I found out just what I needed. I such a lot indisputably will make certain to do not forget this web site and give it a glance a continuing.
Hey there, You’ve done an excellent job. I’ll definitely digg it and personally recommend to my friends. I am sure they’ll be benefited from this site.
Awesome and really informative post here. I very much am into sites that have to do with building muscle, so this is refreshing to me to discover what you have here. Keep up the great work! how to lose weight fast
I discovered your blog post web site online and appearance many of your early posts. Keep within the good operate. I just additional encourage RSS feed to my MSN News Reader. Seeking toward reading a lot more from you finding out at a later time!…
Very interesting subject , thanks for putting up.
Some genuinely wonderful work on behalf of the owner of this internet site , absolutely outstanding content material .
Congratulations on having one of the most sophisticated blogs Ive come across in some time! Its just incredible how much you can take away from something simply because of how visually beautiful it is. Youve put together a great blog space –great graphics, videos, layout. This is definitely a must-see blog!
Thank you for sharing this good article. Very inspiring! (as always, btw)