0

I need to convert this 20140815

into 15.08.2014 and into 15.08.2014 00:00:00

How do I do that, what opportunities are there in Java

4
  • 6
    What research have you done so far, and what have you tried? Hint: SimpleDateFormat... Commented Aug 15, 2014 at 12:47
  • 2
    And Date object has no format. only String has format. You want to do string->string conversion or parsing string to Date? Commented Aug 15, 2014 at 12:48
  • i want only a string conversion / parsing and not string to date Commented Aug 15, 2014 at 12:52
  • @JonSkeet date format? Too complicated and unnecessary. This can be done with simple string manipulation. Simple==best. Commented Aug 16, 2014 at 0:49

2 Answers 2

4

You could use SimpleDateFormat as follows

SimpleDateFormat inputFormat = new SimpleDateFormat("yyyyMMdd");
SimpleDateFormat outputFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");

Date date = inputFormat.parse("20140815");
String result = outputFormat.format(date);
Sign up to request clarification or add additional context in comments.

1 Comment

It would be worth specifying both a time zone (UTC) and a Locale (e.g. US English). Even though this particular format doesn't use any locale-specific symbols, it's a good habit to get into... and as there are time zones where midnight doesn't exist, you can get some weird behaviour that way if you're not careful, too.
1

Why bother with Dates... just use Strings:

String output = input.replaceAll("(....)(..)(..)", "$3.$2.$1"); 

or

String output = input.replaceAll("(....)(..)(..)", "$3.$2.$1 00:00:00"); 

1 Comment

You would bother with date parsing formatting because: a) it will validate that you really have got appropriate date; b) it invites you to actually maintain a more sensible representation (rather than string) for longer. I'm always suspicious of "convert from date format X to date format Y" tasks, because normally you should parse date-related data as soon as you can, and format it as late as you can. Those two points of code are rarely the same point, in my experience.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.