Convert string to DateTime object

Two C# functions that may be useful in accepting date/time strings of various formats:

        /// <summary>
/// Converts date string value, of various formats into DateTime object.
/// Example formats are DDMMYYYY,DD/MM/YYYY,MM/dd/YYYY,MMDDYYYY,...
/// </summary>
/// <param name="dateValue">date string</param>
/// <returns>resulting DateTime object</returns>
public DateTime ConvertDateStringToDateTime(string dateValue) {
string[] dateFormats = { "MM/yyyy",
"M/d/yyyy", "M/dd/yyyy", "MM/dd/yyyy",
"dd/MM/yyyy", "ddMMyyyy","dd/MM/yyyy","MMddyyyy",
"MM-dd-yyyy" };
try {
return DateTime.ParseExact(dateValue, dateFormats, CultureInfo.CurrentCulture, DateTimeStyles.None);
} catch (FormatException fe) {
throw new DataException(dateValue + ": " + fe.Message);
}
}

/// <summary>
/// Converts a time string of various formats into a DateTime object.
/// Example formats are: 7:00,700AM, 7:00AM, 7:00A, 0700AM, 07:00 AM, ...
/// </summary>
/// <param name="timeValue">time string</param>
/// <returns>resulting DateTime object</returns>
public DateTime ConvertTimeStringToDateTime(string timeValue) {
string[] timeFormats = {"HHmm","Hmmtt",
"H:mm", "H:mmtt", "H:mmt", "HHmmtt", "HH:mm tt", "HH:mmtt","HH:mmt", "HHmmtt", "HHMMt"};
// DateTime string cannot be blank, so if it is, assume "00:00"
if (string.IsNullOrEmpty(timeValue)) timeValue = "00:00";
try {
return DateTime.ParseExact(timeValue.ToUpper(), timeFormats, CultureInfo.CurrentCulture, DateTimeStyles.None);
} catch (FormatException fe) {
throw new DataException(timeValue + ": " + fe.Message);
}
}

0 comments: