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

标签 c# datetime

我正在将时间现在 与存储在数据库某处的时间进行比较。数据库中存储的时间格式为“yyyyMMddHHmmss”。例如,数据库可能会为存储的时间值返回 201106203354。然后我使用一个函数将时间现在与从数据库中读取的时间进行比较。

我现在在做什么:

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

我想做什么:

与其拆分格式化的日期时间字符串,并单独创建和分配六个变量以传递给函数,我想知道是否有某种方法可以简单地将格式化的日期时间字符串转换为 日期时间

请查看我的代码,因为它将有助于解释我显然无法解释的内容......

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

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";
        }

所以,很简单,我想比较两个格式均为“yyyyMMddHHmmss”的日期,或者如果这不可能,我想将之前的日期字符串转换为日期时间。

我确定我在这里遗漏了一些东西,我会回去再读一遍,但请随时问我任何我不清楚的地方。

谢谢, 埃文

最佳答案

您正在寻找 ParseExact :

DateTime.ParseExact(timeStamp, "yyyyMMddHHmmss", CultureInfo.InvariantCulture)

关于c# - 将格式化的日期字符串转换为 DateTime(int,int,int,int,int,int) 以传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7379794/

相关文章:

c# - 是否有用于 C# 的良好、高性能的 unsigned BigInteger 类型?

c# - Autofac IComponentContext.Resolve<Type> 是服务定位器模式吗

C# Linq group by DateTime 忽略小时和分钟

.net - 如何测试依赖于事件发生日期的功能?

java - 无法解析的日期 : "2018-08-02T14:24:40.040353"

c# - 对于涉及跨源请求的 SSO 流,在 iOS 12 中阻止了强制执行 SameSite 策略的 Cookie

c# - 绑定(bind)到显式接口(interface)实现的 SortDescription

c# - MEF 从网络共享文件夹加载插件

mysql - 从不同日期datetime mysql字段中选择特定时间

c# - 格式异常:String was not recognized as a valid DateTime