1

I was wondering if Java Date format can do something like this 2 0 1 3 0 1 3 1, where a space is inserted between each digit. So far I can use this code to make it work.

DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
dateString = dateFormat.format(date).replace("", " ").trim();

But I was hoping I can just create a date format to do it all.

Thanks in advance.

Souloikj
  • 360
  • 2
  • 9
  • 19

3 Answers3

2

Your approach is about as simple as possible.

There is no way to do this within a date format specification (not even with Joda time, as someone else mentioned).

Out of interest, why do you want spaces between the digits like that? It seems unusual?

ᴇʟᴇvᴀтᴇ
  • 12,285
  • 4
  • 43
  • 66
0

I suggest that you write a subclass of DateFormat. You will encapsulate your formatting rule.

Aaron Kurtzhals
  • 2,036
  • 3
  • 17
  • 21
  • This is not much better then doing it outside `DateFormat`. In your case you will have to encapsulate this code (`dateFormat.format(date).replace("", " ").trim()`) into your subclass implementation – Andremoniy Jan 18 '13 at 19:40
0

I use:

private final static SimpleDateFormat MSG_DATE_FORMAT = new SimpleDateFormat("yyyy MM dd'T'HHmmssSSSZ");
...
String timeStamp = MSG_DATE_FORMAT.format( new Date() );
Snake
  • 785
  • 1
  • 5
  • 13
  • 2
    `replace("", " ")` adds a space character between all the letters and also at both ends. The `trim()` removes the unwanted whitespace from the ends, retaining the spaces inside the string. – ᴇʟᴇvᴀтᴇ Jan 18 '13 at 19:44
  • It would be better if you will firstly check the facts, and then posting your conclusions. `replace("", " ")` works fine – Andremoniy Jan 18 '13 at 19:49
  • point taken and lesson learned but does my answer 'answer' his question? aetheria's accepted answer doesn't even give him an answer. – Snake Jan 18 '13 at 20:09