gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:38:46 30 4
gpt4 key购买 nike

我正在将时间现在 与存储在数据库某处的时间进行比较。数据库中存储的时间格式为“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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com