check if date time string contains time

后端 未结 5 1787
鱼传尺愫
鱼传尺愫 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:31

    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.

提交回复
热议问题