将格式化的日期字符串转换为DateTime(int,int,int,int,int,int)以传递给函数

3 c# datetime

我将现在的时间与存储在数据库中的某个时间进行比较.存储在数据库中的时间格式为"yyyyMMddHHmmss".例如,数据库可以返回201106203354以获得存储的时间值.然后我使用函数将现在的时间与从数据库读入的时间进行比较.

我现在在做什么:

  1. 创建6个int变量
  2. 从格式化的日期字符串中获取子字符串,并将子字符串转换为int32.
  3. 将6个int变量传递给函数.

我想做什么:

而不是分割格式化的日期时间字符串,并单独创建和分配六个变量传递给函数,我想知道是否有一些方法可以简单地将格式化的日期时间字符串转换为DateTime.

请看我的代码,因为它有助于解释我显然不能...

现在通过时间以及从数据库读取的时间:

Private void passTime()
{
            string timeStamp;
            int year, month, day, hour, minutes, seconds;

            DateTime dt = DateTime.Now;

            timeStamp = dt.ToString("yyyyMMddHHmmss");

            year = Convert.ToInt32(timeStamp.Substring(0, 4));
            month = Convert.ToInt32(timeStamp.Substring(4, 2));
            day = Convert.ToInt32(timeStamp.Substring(6, 2));
            hour = Convert.ToInt32(timeStamp.Substring(8, 2));
            minutes = Convert.ToInt32(timeStamp.Substring(10, 2));
            seconds = Convert.ToInt32(timeStamp.Substring(12, 2));

            MessageBox.Show(GetDifferenceDate(
                            new DateTime(year,month,day,hour,minutes,seconds),
                            // Example time from database
                            new DateTime(2011, 08, 11, 11, 40, 26)));
}

static string GetDifferenceDate(DateTime date1, DateTime date2)
        {
            if (DateTime.Compare(date1, date2) >= 0)
            {
                TimeSpan ts = date1.Subtract(date2);
                return string.Format("{0} days",
                    ts.Days);
            }
            else
                return "Not valid";
        }
Run Code Online (Sandbox Code Playgroud)

所以,很简单,我想比较两个格式为"yyyyMMddHHmmss"的日期,或者如果这是不可能的,我想将之前的Date字符串转换为DateTime.

我确定我在这里遗留了一些东西,我会回去再读一遍,但请随时问我一些我不清楚的事情.

谢谢,埃文

SLa*_*aks 6

您正在寻找ParseExact:

DateTime.ParseExact(timeStamp, "yyyyMMddHHmmss", CultureInfo.InvariantCulture)
Run Code Online (Sandbox Code Playgroud)