
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.
Whats Going down i’m new to this, I stumbled upon this I’ve found It absolutely useful and it has helped me out loads. I’m hoping to give a contribution & aid other users like its aided me. Great job.
Wow! This can be one particular of the most useful blogs We have ever arrive across on this subject. Actually Great. I’m also an expert in this topic so I can understand your hard work.
construction jobs are on the rise again these days because the recession is almost over**
So funcy to see the article within this blog. Thank you for posting it
i would be busy again doing some home decors this coming christmas, i’d be buying some new decors for the season;;
Du er da godt nok hårdt ramt af spam kommentarer
Wow! This could be one particular of the most helpful blogs We’ve ever arrive across on this subject. Actually Great. I am also an expert in this topic so I can understand your hard work.
Howdy! I simply would like to give a huge thumbs up for the good data you have here on this post. I will probably be coming again to your weblog for more soon.
I would like to consider the chance of saying thanks to you for your professional advice I have continually enjoyed going to your site. We’re looking forward to the commencement of my school research and the complete preparing would never have been complete without surfing your site. If I could be of any help to others, I’d personally be ready to help as a result of what I have gained from here.
Regularly I don’t put up on weblogs, however i would like to say that this particular set up genuinely pressured me personally to do this! seriously wonderful publish
Wonderful goods from you, man. I’ve understand your stuff previous to and you are just extremely great. I really like what you’ve acquired here, certainly like what you are saying and the way in which you say it. You make it enjoyable and you still take care of to keep it wise. I cant wait to read far more from you. This is really a terrific website.
I’m new to your blog and i really appreciate the nice posts and great layout.;;*-”
I like looking through and I think this website got some truly utilitarian stuff on it! .
assisted living is nice if you got some people and a home that cares very much to its occupants**
with thanks with regard to the particular article i have been on the lookout with regard to this kind of advice on the net for sum time these days and so with thanks
every sales manager and store owner should have a training in sales management’
– Gulvafslibning | Kurt Gulvmand Fantastic goods from you, man. I’ve understand your stuff previous to and you’re just extremely magnificent. I really like what you have acquired here, really like what you’re stating and the way in which you say it. You make it entertaining and you still take care of to keep it smart. I cant wait to read far more – Gulvafslibning | Kurt Gulvmand again from you. Thanks For Share .
thank you for sharing – Gulvafslibning | Kurt Gulvmand with us, I conceive – Gulvafslibning | Kurt Gulvmand genuinely stands out : D.
very nice post, i undoubtedly enjoy this fabulous website, keep on it
hey all, I used to be simply checking out this weblog and I really admire the idea of the article, and have nothing to do, so if anybody want to to have an engrossing convo about it, please contact me on AIM, my identify is heather smith
Hello. Very nice site!! Man .. Excellent .. Amazing .. I’ll bookmark your site and take the feeds also…I am satisfied to locate numerous useful info right here within the article. Thanks for sharing…
There are a few interesting points in time in this post but I don’t know if I see they all center to heart. There is some validity but I most certainly will take hold opinion until I consider it further. Great article , thanks and we want far more! Put into FeedBurner likewise
There are a couple of fascinating points on time in this post but I don’t know if all of them center to heart. There may be some validity but I’m going to take hold opinion until I investigate it further. Excellent post , thanks so we want a lot more! Put into FeedBurner as well
To your organization online business owner, releasing an important company is the bread so butter inside of their opportunity, and choosing a wonderful child care company often means the particular between a victorious operation this is. how to start a daycare
My husband and i ended up being very cheerful when Ervin could finish off his investigation through the ideas he came across from your weblog. It is now and again perplexing to simply happen to be giving out key points which others could have been trying to sell. So we know we have you to be grateful to because of that. The explanations you made, the straightforward web site navigation, the friendships you help foster – it is many fabulous, and it’s helping our son and the family know that this idea is fun, and that’s incredibly vital. Thanks for all the pieces!
I would really love to guest post on your blog.:.”~*
Wonderful site. Lots of helpful info here. I¡¦m sending it to some buddies ans additionally sharing in delicious. And certainly, thank you for your effort!
the morning fresh air is the best, i have asthma and i love to get some fresh air::
Hrmm that was weird, my comment got eaten. Anyway I wanted to say that it’s wonderful to know that someone else also mentioned this as I had trouble finding the same info elsewhere. This was the first position that told me the answer. Thanks.
Youre so cool! I dont suppose Ive read anything such as this prior to. So nice to find somebody by incorporating original applying for grants this subject. realy i appreciate you for starting this up. this site is a thing that is required on the net, a person if we do originality. valuable purpose of bringing new stuff towards internet!
The guidelines you provided allow me to share extremely precious. It been found this kind of pleasurable surprise to obtain that anticipating me while i awoke today. They’re constantly to the issue and straightforward to recognise. Thanks a ton to the valuable ideas you’ve got shared the following.
european vacations are very exciting sepcially if you got to visit many places at once,.
There couple of interesting points in time in this post but I don’t know if all of them center to heart. There is certainly some validity but I am going to take hold opinion until I take a look at it further. Excellent write-up , thanks so we want much more! Put into FeedBurner as well
You’re the best, It’s posts like this that keep me coming back and checking this weblog regularly, thanks for the info!
Hello. i can see that you are a really great blogger,
This site is usually a walk-through its the knowledge you wished concerning this and didn’t know who need to. Glimpse here, and you’ll certainly discover it.
I have been searching for this information for quite some times. About three hours of online searching, at last I found it in your blog. I wonder why Yahoo dont display this kind of good websites in the first page. Usually the top search engine results are full of rubbish. Perhaps its time to use another search engine.
oh cool, this information is really useful and definately is comment worthy! hehe. I’ll see if I can try to use some of this information for my own blog. Thanks!
Hi, I was studying the net and I ran into your blog. Keep in the great function.
Can I simply say what a relief to seek out someone who truly is aware of what theyre speaking about on the internet. You definitely know tips on how to deliver an issue to light and make it important. Extra folks have to learn this and understand this facet of the story. I cant consider youre not more widespread since you definitely have the gift.
I am writing to let you understand what a extraordinary discovery my cousin’s daughter had going through your web page. She realized a lot of details, including how it is like to have a wonderful helping style to have certain people without problems gain knowledge of a number of grueling matters. You really surpassed her expected results. Many thanks for giving the helpful, healthy, revealing as well as cool tips about that topic to Evelyn.
Fantastic goods from you, man. I’ve understand your stuff previous to and you are just too fantastic. I actually like what you have acquired here, certainly like what you are saying and the way in which you say it. You make it entertaining and you still care for to keep it wise. I can’t wait to read far more from you. This is really a terrific site.
I conceive other website proprietors should take this internet site as an model, very clean and good user pleasant style .
Pretty nice post, thanks for the awesome article. I’m having troubles subscribing to your blogs feed. Thought I’d let you know
I needed to write you that little bit of remark to help give many thanks once again with your striking solutions you’ve featured on this website. It was certainly extremely open-handed of you to grant publicly what exactly most people would have made available as an e-book to generate some profit for themselves, specifically seeing that you could have done it if you considered necessary. Those solutions in addition acted like a fantastic way to realize that some people have similar interest similar to mine to know good deal more related to this condition. I am certain there are some more enjoyable moments ahead for individuals who scan through your site.
somtimes i also sell stuffs on craigslists because there are many users in it*
I just love to read new topics from you blog.~~~`”
I am typically to running a blog and i really recognize your content. The article has actually peaks my interest. I am going to bookmark your website and keep checking for new information.
ut officia at et et aliquam dignissimos corporis. cupiditate fuga repudiandae atque et.
We still cannot quite believe that It was not respectable come to be the type staring at the important points located on yuor web blog. Our family and i also are sincerely thankful for use on your generosity too as for giving me possibility pursue our chosen profession path. I appreciate you important information I had on your web-site.