C# 检查日期时间字符串是否包含时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15893339/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 18:18:46  来源:igfitidea点击:

check if date time string contains time

c#datetimetime

提问by Hasitha Shan

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:012)2010/APRIL/02 17:10:003)10/02/10 03:30:34

1) 1980/10/11 12:00:012) 2010/APRIL/02 17:10:003)10/02/10 03:30:34

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

日期可以是任何格式,后跟24hr表示法的时间。

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

但这仅适用于无1)类型时间戳。请问如何完成有关如何检测此日期时间字符串中是否存在时间元素的任务。非常感谢 :)

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

可能的匹配如何验证“日期和时间”字符串是否只有时间?

INFOthe three answers provided by Arun Selva Kumar,Guru Kara,Patipol Paripoonnanondaare 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 :)

INFOArun Selva Kumar, Guru Kara,提供的三个答案Patipol Paripoonnanonda都是正确的,并检查了时间并符合我的目的。但我Guru Kara仅根据易用性和他给出的解释来选择s 答案。非常感谢 :) 非常感谢你们所有人 :)

采纳答案by Guru Kara

The date time components TimeOfDayis what you need.

日期时间组件TimeOfDay正是您所需要的。

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

MSDN 说“与 Date 属性不同,它返回一个 DateTime 值来表示一个没有其时间组件的日期,TimeOfDay 属性返回一个 TimeSpan 值,它表示一个 DateTime 值的时间组件。”

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

这是一个考虑到所有场景的示例。
由于您确定可以使用DateTime.Parse其他格式,请使用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");
}

回答by Arun Selva Kumar

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

您可以尝试使用此处列出的其他格式说明符,http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

回答by Pat

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!

希望这可以帮助!

回答by Kasper van den Berg

Combining the answers of Guru Karaand Patipol Paripoonnanondawith the .net globalisation API results in:

Guru KaraPatipol Paripoonnanonda的答案与 .net 全球化 API相结合,结果:

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 TimeOfDayindicates 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.
  • 检测明确的午夜时间(例如“2015-02-26T00:00”);
  • 仅在TimeOfDay指示午夜或没有明确时间时搜索字符串;和
  • 查找本地格式的明确午夜时间和 .net 可以解析的任何格式的任何非午夜时间。

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.
  • 未检测到非文化本地格式的明确午夜时间;
  • 未检测到少于两个部分的明确午夜时间;和
  • 不如 Guru Kara 和 Patipol Paripoonnanonda 的方法简单和优雅。

回答by Zephryl

Here's what I'm going with for now. It may not be perfect, but likely better than considering any 12am datetime as not having a time. The premise is that if I tack a full time specification on the end it will parse if it's just a date but fail if it already has a time component.

这就是我现在要做的。它可能并不完美,但可能比将任何 12 点约会时间视为没有时间要好。前提是,如果我在最后加上一个完整的时间规范,它会解析它是否只是一个日期,但如果它已经有一个时间组件就会失败。

I had to make the assumption that there's not some valid, date/time that has 7 non-white-space characters or less. It appears that "1980/10" parses, but not "1980/10 01:01:01.001".

我不得不假设没有一些有效的日期/时间具有 7 个或更少的非空白字符。似乎“1980/10”解析,但不是“1980/10 01:01:01.001”。

I've included various test cases. Feel free to add your own and let me know if they fail.

我已经包含了各种测试用例。随意添加您自己的,如果它们失败,请告诉我。

public static bool IsValidDateTime(this string dateString, bool requireTime = false)
{
    DateTime outDate;
    if(!DateTime.TryParse(dateString, out outDate)) return false;

    if (!requireTime) return true;
    else
    {
        return Regex.Replace(dateString, @"\s", "").Length > 7 
&& !DateTime.TryParse(dateString + " 01:01:01.001", out outDate);
    }
}

public void DateTest()
{
    var withTimes = new[]{
    "1980/10/11 01:01:01.001",
    "02/01/1980 01:01:01.001",
    "1980-01-01 01:01:01.001",
    "1980/10/11 00:00",
    "1980/10/11 1pm",
    "1980-01-01 00:00:00"};

    //Make sure our ones with time pass both tests
    foreach(var date in withTimes){
        Assert.IsTrue(date.IsValidDateTime(), String.Format("date: {0} isn't valid.", date));
        Assert.IsTrue(date.IsValidDateTime(true), String.Format("date: {0} does have time.", date));
    }

    var withoutTimes = new[]{
    "1980/10/11",
    "1980/10",
    "1980/10 ",
    "10/1980",
    "1980 01",
    "1980/10/11 ",
    "02/01/1980",
    "1980-01-01"};

    //Make sure our ones without time pass the first and fail the second
    foreach (var date in withoutTimes)
    {
        Assert.IsTrue(date.IsValidDateTime(), String.Format("date: {0} isn't valid.", date));
        Assert.IsFalse(date.IsValidDateTime(true), String.Format("date: {0} doesn't have time.", date) );
    }

    var bogusTimes = new[]{
    "1980",
    "1980 01:01",
    "80 01:01",
    "1980T01",
    "80T01:01",
    "1980-01-01T01",
    };

    //Make sure our ones without time pass the first and fail the second
    foreach (var date in bogusTimes)
    {
        DateTime parsedDate;
        DateTime.TryParse(date, out parsedDate);
        Assert.IsFalse(date.IsValidDateTime(), String.Format("date: {0} is valid. {1}", date, parsedDate));
        Assert.IsFalse(date.IsValidDateTime(true), String.Format("date: {0} is valid. {1}", date, parsedDate));
    }
}