function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
aj2taylo2aj2taylo2 

Convert String to Date

I'm developing an import tool through a VF page, and the uploaded CSV will contain a date field.

 

The date field may arrive in different formats (YYYY/MM/DD;  MON-DD, YY, etc).  Is there a common library for this, or will I have to write a regex utility to do the conversion from string to date based on the string format?

Best Answer chosen by Admin (Salesforce Developers) 
sfdcfoxsfdcfox
You can try using Date.parse, but it may not get it right 100%. When you doubt your input, it's probably best to use an algorithm under your control, so I'd say you'd want to write your own.

However, you won't need regex, I don't think. Take a look at String.splitByCharacterType for a function that can make your life easier. This will return each group of elements that are similar in character type as separate elements. You can then use String.isAlpha, String.isNumeric to determine the various parts of the string, and Integer.valueOf to convert those to numbers. Date.newInstance will construct proper data for storing in the database, of course. But, this depends on how much flexibility you need. Date.parse will usually correctly guess dates based on the user's locale. If the locale is unknown or may not match the user's locale, then you'll need to write your own library anyways.

All Answers

sfdcfoxsfdcfox
You can try using Date.parse, but it may not get it right 100%. When you doubt your input, it's probably best to use an algorithm under your control, so I'd say you'd want to write your own.

However, you won't need regex, I don't think. Take a look at String.splitByCharacterType for a function that can make your life easier. This will return each group of elements that are similar in character type as separate elements. You can then use String.isAlpha, String.isNumeric to determine the various parts of the string, and Integer.valueOf to convert those to numbers. Date.newInstance will construct proper data for storing in the database, of course. But, this depends on how much flexibility you need. Date.parse will usually correctly guess dates based on the user's locale. If the locale is unknown or may not match the user's locale, then you'll need to write your own library anyways.
This was selected as the best answer
aj2taylo2aj2taylo2

Thanks sfdcfox;  I'm waiting for some sample files to get an idea of how much variety there'll be, so will see if I can get away with Date.parse or if I need to do my own utility.