check if date time string contains time

34,951

Solution 1

The date time components TimeOfDay is what you need.

MSDN says "Unlike the Date property, which returns a DateTime value that represents a date without its time component, the TimeOfDay property returns a TimeSpan value that represents a DateTime value's time component."

Here is an example with consideration of all your scenarios.
Since you are sure of the format you can use DateTime.Parse else please use DateTime.TryParse

var dateTime1 = System.DateTime.Parse("1980/10/11 12:00:00");
var dateTime2 = System.DateTime.Parse("2010/APRIL/02 17:10:00");
var dateTime3 = System.DateTime.Parse("10/02/10 03:30:34");
var dateTime4 = System.DateTime.Parse("02/20/10");

if (dateTime1.TimeOfDay.TotalSeconds == 0) {
    Console.WriteLine("1980/10/11 12:00:00 - does not have Time");
} else {
    Console.WriteLine("1980/10/11 12:00:00 - has Time");
}

if (dateTime2.TimeOfDay.TotalSeconds == 0) {
    Console.WriteLine("2010/APRIL/02 17:10:00 - does not have Time");
} else {
    Console.WriteLine("2010/APRIL/02 17:10:00 - Has Time");
}

if (dateTime3.TimeOfDay.TotalSeconds == 0) {
    Console.WriteLine("10/02/10 03:30:34 - does not have Time");
} else {
    Console.WriteLine("10/02/10 03:30:34 - Has Time");
}

if (dateTime4.TimeOfDay.TotalSeconds == 0) {
    Console.WriteLine("02/20/10 - does not have Time");
} else {
    Console.WriteLine("02/20/10 - Has Time");
}

Solution 2

Try this,

DateTime myDate;
if (DateTime.TryParseExact(inputString, "dd-MM-yyyy hh:mm:ss", 
    CultureInfo.InvariantCulture, DateTimeStyles.None, out myDate))
{
    //String has Date and Time
}
else
{
    //String has only Date Portion    
}

You can try using other format specifiers as listed here, http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

Solution 3

Combining the answers of Guru Kara and Patipol Paripoonnanonda with the .net globalisation API results in:

bool HasExplicitTime(DateTime parsedTimestamp, string str_timestamp)
{
    string[] dateTimeSeparators = { "T", " ", "@" };
    string[] timeSeparators = {
        CultureInfo.CurrentUICulture.DateTimeFormat.TimeSeparator,
        CultureInfo.CurrentCulture.DateTimeFormat.TimeSeparator,
        ":"};

    if (parsedTimestamp.TimeOfDay.TotalSeconds != 0)
        return true;

    string[] dateOrTimeParts = str_timestamp.Split(
            dateTimeSeparators,
            StringSplitOptions.RemoveEmptyEntries);
    bool hasTimePart = dateOrTimeParts.Any(part =>
            part.Split(
                    timeSeparators,
                    StringSplitOptions.RemoveEmptyEntries).Length > 1);
    return hasTimePart;
}

This approach:

  • detects explicit midnight times (e.g. "2015-02-26T00:00");
  • only searches the string when TimeOfDay indicates midnight or no explicit time; and
  • finds explicit midnight times in local format and any non midnight time in any format that .net can parse.

Limitations:

  • explicit midnight times in non culture local format are not detected;
  • explicit midnight times with less than two parts are not detected; and
  • less simple and elegant than the approaches of Guru Kara and Patipol Paripoonnanonda.
Share:
34,951
Hasitha Shan
Author by

Hasitha Shan

Updated on June 07, 2020

Comments

  • Hasitha Shan
    Hasitha Shan almost 4 years

    I have run into an issue. I'm obtaining a date time string from the database and and some of these date time strings does not contain time. But as for the new requirement every date time string should contain the time like so,

    1)1980/10/11 12:00:01 2)2010/APRIL/02 17:10:00 3)10/02/10 03:30:34

    Date can be in any format followed by the time in 24hr notation.

    I tried to detect the existence of time via the following code,

    string timestamp_string = "2013/04/08 17:30";
    DateTime timestamp = Convert.ToDateTime(timestamp_string);
    string time ="";
    
    if (timestamp_string.Length > 10)
    {
        time = timestamp.ToString("hh:mm");
    }
    else {
        time = "Time not registered";
    }
    
    MessageBox.Show(time);
    

    But this only works for the No 1) type timestamps. May I please know how to achieve this task on how to detect if the time element exist in this date time string. Thank you very much :)

    POSSIBLE MATCH How to validate if a "date and time" string only has a time?

    INFO the three answers provided by Arun Selva Kumar,Guru Kara,Patipol Paripoonnanonda are all correct and checks for the time and serves my purpose. But I select Guru Karas answer solely on ease of use and for the explanation he has given. Thank you very much :) very much appreciated all of you :)

  • Hasitha Shan
    Hasitha Shan about 11 years
    hey thanx for the reply :) i will try this out n post back :)
  • Akanksha Gaur
    Akanksha Gaur about 11 years
    If the string is not a date, your else will give wrong answer. You need use another DateTime.TryParseExact for just date format.
  • Hasitha Shan
    Hasitha Shan about 11 years
    hey i tried this but it always give the error message ? do you knwo y?? string a = "08/04/2013 17:34:00"; DateTime myDate; if (DateTime.TryParseExact(a, "dd/MM/yyyy hh:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out myDate)) { MessageBox.Show("Correct"); //String has Date and Time } else { MessageBox.Show("Error"); //String has only Date Portion }
  • Arun Selva Kumar
    Arun Selva Kumar about 11 years
    @Hasitha you are getting Error cos, the format specifier you had given is wrong "hh" denotes hours in 12 hours format, use HH for the format specified. Kindly refer the link I had provided for the list of formats for datetime!
  • Hasitha Shan
    Hasitha Shan about 11 years
    hey thanx for the reply i will check this and post back :)
  • Hasitha Shan
    Hasitha Shan about 11 years
    hey thank you for the reply :) i will go thru ths n post back :)
  • Pat
    Pat about 11 years
    Have you had a chance to try it? Please let me know.
  • Hasitha Shan
    Hasitha Shan about 11 years
    hey..hi..sorry for the delay..i selected an answer and I explained the reason why in the question itself.. many thanks for help :) very much appreciated.
  • Kasper van den Berg
    Kasper van den Berg about 9 years
    -1: This method fails on any datetime string with a specified time of midnight; e.g. for "2015-02-26T00:00" I expect a result of "Has Time", but System.DateTime.Parse("2015-02-26T00:00").TimeOfDay.TotalSec‌​onds evaluates to 0.0.
  • Kasper van den Berg
    Kasper van den Berg about 9 years
    Date time strings sometimes use 'T' (e.g. dates in ISO 8601 standard format) or '@' ; edited to improve
  • Tony Pulokas
    Tony Pulokas over 8 years
    In the first sentence, the name of the method is spelled wrong. I tried to edit it, but the stackoverflow UI says that edits must be at least six characters. Also, I agree with Kasper van den Berg that this answer does not meet the requirements.
  • Zephryl
    Zephryl almost 8 years
    I agree with Kasper. This doesn't account for midnight being specified as a valid time.
  • hypehuman
    hypehuman almost 7 years
    As @KaspervandenBerg pointed out, not all formats have a space between the date and the time. And the format could also have a space even if there is no time, e.g. "Jun 29, 2017". If you are able to get a comprehensive list of all date/time formats used in your database, you might be able to use this trick. But it sounds like that's not the case.
  • Jeff Mergler
    Jeff Mergler over 6 years
    As others have noted assuming a space will be a reliable delimiter could get you into trouble down the road, ref. en.wikipedia.org/wiki/ISO_8601
  • Isaac Vidrine
    Isaac Vidrine over 2 years
    I have to disagree - If total seconds is 0, then you know in fact the time would be midnight right?