+ Start a Discussion
drdocbdrdocb 

Create Datetime from Date field and text (time) field

I have just started learning APEX but have old C , basic experience.

 

I am trying to use a date field and time field for my object to allow smoother input of scheduling appointments. I have converted the date to startdate string and time is already a string - I can combine both and was using Valueof method to create the datetime field but the format is invalid as datetime wants yyyy-mm-dd hh:mm:ss and my string is coming out mm/dd/yyyy hh:mm AM or PM.

 

I guess i can break everything down to day, month, year and then reconstruct but hoped there was a less cumbersome way.  Want the date / time input to input the way the default event page does it.

 

Any help for this APEX novice is appreciated

bob_buzzardbob_buzzard

Unfortunately I think you are out of luck here.  The datetime parse expects the String to be in a specific format - there's no additional version of the method that allows you to specify the format.

brountrebrountre

Hi this class should do what your asking:

public class zUtility {
	public static datetime stringToDateTime(String datestring)
	{
		/*
			Format of incoming string is : mm/dd/yyyy hh:mm AM
		*/
		// Split date part of string
		list<String> datelist = new list<String>();
		datelist = datestring.split('/',3);
		Integer imonth = Integer.valueOf(datelist[0]);
		Integer iday = Integer.valueOf(datelist[1]);
		Integer iyear = Integer.valueOf(datelist[2].substring(0,4));
		
		// Split time part of string		
		Integer colonpos = datestring.indexOf(':');
		Integer stringlen = datestring.length();
		Integer ihour = Integer.valueOf(datestring.substring(colonpos - 2,colonpos ));
		Integer imin = Integer.valueOf(datestring.substring(colonpos + 1, colonpos + 3));
		Integer isec = 0;
		String sampm = datestring.substring(stringlen - 2, stringlen);
		if (sampm == 'PM')
			ihour = ihour + 12;
		
		// Create datetime return type
		datetime parsedDate = datetime.newInstance(iyear, imonth, iday, ihour, imin, isec);
		
		// return datetime formatted date				
		return parsedDate;
	}
	
	public static testmethod void teststringtoDateTime()
	{
		datetime testDate = stringToDateTime('10/14/1972 12:32 PM');
		System.debug(testDate);
	}
}