Please see my comment to the question. Everything is already done for you, just look at the type
System.DateTime
,
http://msdn.microsoft.com/en-us/library/system.datetime.aspx[
^].
To get a time value from string, you can use one of parse methods, please read about them. To write it in a string in required format, use one of
System.DateTime.ToString
methods. The particular format is defined by culture (see
ToString(IFormatProvider)
,
ToString(String, IFormatProvider)
, and
CultureInfo
which implements
IFormatProvider
) and/or string format. For formats, please see:
http://msdn.microsoft.com/en-us/library/az4se3k1.aspx[
^] (standard format strings),
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx[
^] (custom format strings).
[EDIT]
To respond to the follow-up discussion. First, you code sample is wrong. More importantly, your problem cannot be solved in general case. Here is what you should use, basically:
string dateString = "03-04-2012";
System.DateTime dateMonthDayYear = System.DateTime.ParseExact(
dateString,
new string[] { "MM-dd-yyyy" },
null, System.Globalization.DateTimeStyles.None);
System.DateTime dateDayMonthYear = System.DateTime.ParseExact(
dateString,
new string[] { "dd-MM-yyyy" },
null, System.Globalization.DateTimeStyles.None);
System.DateTime dateAmbiguous = System.DateTime.ParseExact(
dateString, new string[] { "dd-MM-yyyy", "MM-dd-yyyy" },
null, System.Globalization.DateTimeStyles.None);
First two interpretation of the date string "03-04-2012" are unambiguous, by the last one is ambiguous, because, without a priory assumptions, you cannot tell if "03" is a month or a day. But, if your input would be "29-04-2012" or "04-29-2012", one of the first to calls to
ParseExact
will throw an exception (use
TryParse
,
TryParseExact
to work without exceptions, if you want), but the third call will give you an unambiguous result; all three cases will work this way just because "29" cannot be a month number.
This way, you cannot allow the user to enter date in arbitrary format without specification of parsing rules, no matter how hard you try.
Practically, you can used fixed custom or standard format, or, as a perfect solution, some UI with date-time picker like
System.Windows.Forms.DateTimePicker
,
http://msdn.microsoft.com/en-us/library/system.windows.forms.datetimepicker.aspx[
^].
Enjoy,
—SA