How to validate if a “date and time” string only h

2019-06-20 07:09发布

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).

8条回答
手持菜刀,她持情操
2楼-- · 2019-06-20 07:48

Use

Convert.ToDateTime(string value, IFormatProviderProvider provider)

Since the string comes in different flavors, provide different format providers as needed.

The order could be:

  • DateOnly
  • Time Only
  • DateTime

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.

查看更多
疯言疯语
3楼-- · 2019-06-20 07:51

Looking at the length of the string will be straight-forward and will support multiple formats. A string with a date and time will most certainly be longer than a string with just a time. However, if your input may have times with high precision (12:30:30:50:20 vs 12/11/11 12:30) and low precision this won't work.

This solution is ideal if you don't need to know the value in the string immediately, and only want to add the default date.

If you support times to the second, for instance, a time will have 8 or less characters and a date-time will have 9 or more.

查看更多
男人必须洒脱
4楼-- · 2019-06-20 07:55
劳资没心,怎么记你
5楼-- · 2019-06-20 07:55

Here's one way to do this without knowing all possible time formats:

CultureInfo provider = CultureInfo.CurrentCulture;
DateTime time;
DateTime datetime;
bool isTime = DateTime.TryParse(dateString, provider, DateTimeStyles.NoCurrentDateDefault, out time) 
            && time.Date == DateTime.MinValue.Date
            && DateTime.TryParse(dateString, provider, DateTimeStyles.None, out datetime) 
            && datetime.Date != DateTime.MinValue.Date);

If the string only has a time then the first TryParse will set the date part to 1/1/0001 or DateTime.MinValue.Date and the second TryParse will set the date part to the current date. This will work unless it is run by Doctor Who after travelling back in time to 1/1/0001.

查看更多
ら.Afraid
6楼-- · 2019-06-20 07:57

Given that the time can be in various formats (12/24?) it would be best to user several patterns, in some pre-defined order, trying to parse with each and resolving when the first succeeds.

查看更多
走好不送
7楼-- · 2019-06-20 07:59

This might not be the best but it answers your question:

    string dateString = "9:53AM";
    if (!dateString.Contains('/')))
    {
        dateString = DateTime.Now.ToShortDateString() + " " + dateString;
    }
查看更多
登录 后发表回答