check if date time string contains time

后端 未结 5 1875
鱼传尺愫
鱼传尺愫 2021-02-06 23:37

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

5条回答
  •  不要未来只要你来
    2021-02-07 00:20

    Date and time are always separated by a space bar. The easiest way would be:

    if (timestamp_string.Split(' ').Length == 2)
    {
        // timestamp_string has both date and time
    }
    else
    {
        // timestamp_string only has the date
    }
    

    This code assumes the date always exists.

    If you want take it further (in case the date does not exist), you can do:

    if (timestamp_string.Split(' ')
                        .Select(item => item.Split(':').Length > 1)
                        .Any(item => item))
    {
        // this would work for any string format that contains date, for example:
        // 2012/APRIL/03 12:00:05 -> this would work
        // 2013/04/05 09:00:01 -> this would work
        // 08:50:45 2013/01/01 -> this would also work
        // 08:50:50 -> this would also work
    }
    else
    {
        // no date in the timestamp_string at all
    }
    

    Hope this helps!

提交回复
热议问题