I have a single string variable that stores what could be a full date or a partial date:
1) Full Date: 12/12/2010 12:33 AM
2) Partial Date: 12:33 AM (no date field only time)
I'm trying to figure out what would be the best approach to parse the string to figure out if the string is missing the date string or not. The reason is, in my code if the date is missing I will append a default date to the string (such as 1/1/1900). Keep in mind that the time could be in various formats.
Update - My particular answer to this problem.
As all the "posts" have stated, there are multiple answers to this problem, this is ultimately what I used and hope it can help others*:
public DateTime ProcessDateAndTime(string dateString)
{
string dateAndTimeString = dateString;
string[] timeFormats = new string[]
{
"hh:mm tt", "hh:mm:ss tt",
"h:mm tt", "h:mm:ss tt",
"HH:mm:ss", "HH:mm", "H:mm"
};
// check to see if the date string has a time only
DateTime dateTimeTemp;
if (DateTime.TryParseExact(dateString, timeFormats,
CultureInfo.InvariantCulture.DateTimeFormat, DateTimeStyles.None, out dateTimeTemp))
{
// setting date to 01/01/1900
dateAndTimeString = new DateTime(1900, 1, 1).ToShortDateString() + " " + dateString;
}
return DateTime.Parse(dateAndTimeString);
}
*Note: This method is based on the assumption that there are only a specific amount of time formats used in your application, and that it is guaranteed that a properly formatted date and time, or time only string passed in (pre-validation for removal of garbage text).
ToDateTime(timestamp_string); string time =""; if (timestamp_string. Length > 10) { time = timestamp. ToString("hh:mm"); } else { time = "Time not registered"; } MessageBox. Show(time);
Use the DateTime. TryParseExact method in C# for Date Format validation. They method converts the specified string representation of a date and time to its DateTime equivalent. It checks whether the entered date format is correct or not.
") try: validtime = datetime. datetime. strptime(caminput1, timeformat) #Do your logic with validtime, which is a valid format except ValueError: #Do your logic for invalid format (maybe print some message?).
Use
Convert.ToDateTime(string value, IFormatProviderProvider provider)
Since the string comes in different flavors, provide different format providers as needed.
The order could be:
The convert will throw an format exception if it fails. If you prefer not to have exceptions, use Datetime.TryParse
instead as that returns a boolean.
Depending on how the string is represented you could have more than 3 format providers.
You can try to validate string with a RegEx,
BTW, good regexes for DateTime
validation can be found here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With