my dog learned polymorphism
The moose likes Beginning Java and the fly likes Date formatting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Date formatting" Watch "Date formatting" New topic

Date formatting

Dominic Steng�rd
Ranch Hand

Joined: Feb 05, 2001
Posts: 186
Hey fellow javacoders!

I'll get two Strings from a remote system:
String dateStr = "20080206";
String timeStr = "1215";

I want to convert them into another format:

What would be the most efficient way of doing this?

Thanks in advance!

Dominic Steng�rd<br />Sun Certified Java 2 Programmer
Rob Spoor

Joined: Oct 27, 2005
Posts: 20275


How To Ask Questions How To Answer Questions
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15092

You could try to parse them (for example with SimpleDateFormat) and format the resulting Date object again, but that is probably not the most efficient way. You could just use methods in class String to get the parts that you need and paste them together again.

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Jim Yingst

Joined: Jan 30, 2000
Posts: 18671
Efficiency is overrated, I think. For most programs, IO/database operations are the slowest by far, and the speed of anything else is unimportant. I would try to make the method as easy as possible to understand and modify later if necessary - to do this, SimpleDateFormat is the way to go. It may be a little bit slower than the method Jesper suggests, but the chance that this will ever matter is remarkably small.
[ February 16, 2008: Message edited by: Jim Yingst ]

"I'm not back." - Bill Harding, Twister
Aaron John
Ranch Hand

Joined: May 30, 2005
Posts: 74
Is there any way to do this in reverse?

e.g. you have a date along the lines of 2008-02-19.

How would you end up with a String with something like 20080219 ??

Ulf Dittmer

Joined: Mar 22, 2005
Posts: 42965
Originally posted by Aaron John:
Is there any way to do this in reverse?

That's really the same problem, isn't it? You can either use SimpleDateFormat or string operations.
I agree. Here's the link:
subject: Date formatting
It's not a secret anymore!