chobo2
chobo2

Reputation: 85775

change AM to PM?

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?

Upvotes: 1

Views: 3986

Answers (2)

CmdrTallen
CmdrTallen

Reputation: 2282

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

Upvotes: 1

Mayo
Mayo

Reputation: 10792

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);
  }

Upvotes: 9

Related Questions