views:

162

answers:

2

Hi

I am sending in a strings in with the date part, hour part and minute part and AM/PM Now I want to make this into a DateTime. But I am unsure how to change the time part to AM/PM depending on user choice.

How do I do this?

+6  A: 

You could initialize the time with the date/hour/minute and then add 12 hours if it is PM. Alternatively, you could format the string with the am/pm and convert that to a datetime. I'll see if I can find an example using am/pm.

EDIT: Plenty of documentation in MSDN including a C# example for "2/16/2008 12:15:12 PM".

  DateTime dateValue;
  string dateString = "2/16/2008 12:15:12 PM";
  try {
     dateValue = DateTime.Parse(dateString);
     Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue);
  }   
  catch (FormatException) {
     Console.WriteLine("Unable to convert '{0}'.", dateString);
  }
Mayo
A: 

I like setting a preference by the user for the string format and then using that preference in the ToString().

string userPref = "yyyyMMdd HH:mm";
Console.WriteLine(DateTime.Now.ToString(userPref));
// 20090831 16:44
userPref = "yyyyMMdd hh:mm AMPM";
Console.WriteLine(DateTime.Now.ToString(userPref));
// 20090831 4:44 PM
CmdrTallen