[SalesForce] Convert Text to Date field

How do you populate a text field yyyy-mm into a date field setting the day as 01 as mm/01/yyyy?

Best Answer

Assuming all of your dates will be in yyyy-mm format.

If you're doing this in a Field Update the following formula should work.

DATE(VALUE(LEFT(TextField__c, 4)), VALUE(RIGHT(TextField__c, 2)), 1)

In Apex you could use the following:

String dateString = '2014-09';
Integer year = Integer.valueOf(dateString.subString(0, 4));
Integer month = Integer.valueOf(dateString.subString(5));
Date d = Date.newInstance(year, month, 1);

You could also look into using Date.parse(String) or Date.valueOf(String), but both those methods are a bit of a pain to use.