-2

I have checked and apparently you can't left-pad zero onto an integer. Converting to string and back to integer doesn't work either. Although, what I am trying to do is use the integer for a FOR loop and then send into a JPQL query, using concatenation, which needs the date format to be in XML Gregorian Calendar(YYYY-MM-DD HH:MM:SS).

One way to solve my problem would be to use formatter before sending it into a JPQL query. What I mean to ask is : Is there a better way to do this, in my case?

Here is the relevant piece of code:

for (int month = startMonth; month <= endMonth; month++) {

                    inputDates = "SELECT COUNT(d) FROM Datafile d WHERE d.datafileCreateTime BETWEEN {ts  2013-" +month+ "-01 00:00:00}  AND {ts 2013-" +month+ "-02 23:59:59}";
                    ...
zack2313
  • 101
  • 4
  • 1
    Did you even bother to read something about `String.format()` ?? – Antoniossss Aug 12 '14 at 14:54
  • I would look into the `format` class which will let you specify the number of characters a number has before and after decimals. This should let you achieve what you want. – JustWannaFly Aug 12 '14 at 14:56
  • 2
    Is http://docs.oracle.com/javase/6/docs/api/java/text/DecimalFormat.html what you are looking for? You can convert an int into a two digit number with leading zeros. – JustinKSU Aug 12 '14 at 14:56
  • Hard to tell what this is a duplicate of, since the question starts out about left padding integers with zeros but turns into formatting a date. – David Conrad Aug 12 '14 at 15:38
  • Is there some way to use a GROUP BY in the SQL query, rather than running multiple queries to get the results by month? – David Conrad Aug 12 '14 at 15:40
  • @DavidConrad thanks, but the query seems to accept using formatter. Also I am using JPQL, and I think SQL is different, right? I don't know too much as I only started recently. – zack2313 Aug 12 '14 at 15:57

2 Answers2

4

How about this:

String.format("%010d", 123456);

Details: Formatter

or

org.apache.commons.lang.StringUtils.leftPad("123456", 10, "0");

Details: StringUtils

Adrian
  • 5,571
  • 9
  • 41
  • 68
1

If I understand your question, you need a Date in a specific format, I would recommend using a SimpleDateFormat. That is, something like -

DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String date = sdf.format(new Date());
System.out.println(date);

Output is

2014-08-12 11:06:19
Elliott Frisch
  • 183,598
  • 16
  • 131
  • 226