Showing posts with label date. Show all posts
Showing posts with label date. Show all posts

Wednesday, January 2, 2013

HQL: Query By Date Without The Time

In HQL/JPA There are a couple ways to query off of a date in a database without taking into account the time, but most of them require you fiddle with the date objects before handing them off to the query or to use native SQL functions. 

However, here is a simple way to query, ignoring the time, and only using hibernate expressions.

day(g.transactionDate) = day(:transactionDate) and month(g.transactionDate) = month(:transactionDate) and year(g.transactionDate) = year(:transactionDate)

And here is a link to the relevant Hibernate Docs.

Tuesday, October 16, 2012

Using String.format with Dates, Decimals and other cool things

Formatting Strings can become pretty cumbersome when you need to create a formatter object to handle a variety of different classes. Java does provide a pretty simple way to format many data types with the String.format method, but it can be hard to remember all the ways it can be used. Here are some examples to act as a reminder.

Date/Time

For more date/time formatting see here

Decimals and Money

Gotcha: If you are specifying each argument by it's index (%1, %2, etc) you need to add the '$' before any formatting, i.e. %2$.2f

Special Flags and New Line

You can also use special flags such as negative numbers in parans, zero-padding, and comma grouping
These examples cover the most common use cases of String formatting, but for more information you can check out the javadocs

Friday, July 27, 2012

Using Multiple Date Formats in SpringMVC's InitBinder

The other day I found myself needing my SpringMVC controller to be able to map multiple formats to a date. I was using the CustomDateEditor to map the normal MM/dd/yyyy format, but then I found that I also needed to be able to accept the EEE MMM dd HH:mm:ss zzz yyyy format.

Not being able to find an existing solution, I decided to roll my own. Enjoy.

Below shows how it is used in the controller, the actual editor class, and then the test

Thursday, March 22, 2012

Calculating the number of months between two dates

I've seen a few of these solutions on stackoverflow and I figured it would be worth remembering so, here is how you can calculate how many months are between two dates.



And a test that assumes that this method is in the DateUtils class and that the DateUtils class has an addToDate method (simply using the calendar's add method)