+ Start a Discussion
Kenji775Kenji775 

Date formatting

I know I know, another dumb question.

 

From another system, I get a string that represents a date, ex 03211988, which means March 21, 1988. How to I convert that string into a salesforce date object? I tried the .parse function, but that needs the / to be included in the string, which are not. I suppose I could do a bunch of string manipulation to insert the / but that seems fairly hackish. Any other more elegant ideas?

Best Answer chosen by Admin (Salesforce Developers) 
ThomasTTThomasTT

It's not a dumb question, but answer is "no". There is no method which takes format string to parse. Well... there are elegant solutions for complicated date format (you can find many posts about date format/parse issue), but your example isn't quite complicated. Is this "a bunch of string manipulation" to you?

 

String s = '03211988';
Date d = date.newInstance(
integer.valueOf(s.substring(4,8)),
integer.valueOf(s.substring(0,2)),
integer.valueOf(s.substring(2,4))
);

 

 

ThomasTT

All Answers

ThomasTTThomasTT

It's not a dumb question, but answer is "no". There is no method which takes format string to parse. Well... there are elegant solutions for complicated date format (you can find many posts about date format/parse issue), but your example isn't quite complicated. Is this "a bunch of string manipulation" to you?

 

String s = '03211988';
Date d = date.newInstance(
integer.valueOf(s.substring(4,8)),
integer.valueOf(s.substring(0,2)),
integer.valueOf(s.substring(2,4))
);

 

 

ThomasTT

This was selected as the best answer
Kenji775Kenji775
Thanks a bunch for the help. If that is the best way to do it, then I am fine with it. I'm just always afraid someone will stumble across my code later and ridicule me for having to use things like this :P Anything that works is okay with me personally. Thanks so much.
ThomasTTThomasTT

You can always search the existing posts.

That's a good execuse enough to against those opinions. If you find any post without the solution, that's better execuse rather than "nobody didn't reply to my question". I'm just saying this because myself found many posts about it but couldn't find any solution from them.

 

* I recommend to bookmark/subscribe those posts you find so that you'll see when they find a solution or new API solves the problem.

 

ThomasTT