c# - 从 C# 中的两个字符串变量转换为 DateTime

标签 c# string date datetime

我想将两个字符串变量转换为日期时间变量。 所以像这样...

string day = "05";
string month = "11";
Convert.ToDateTime(day + month + "0000");

这将被上传到 SQL Server smalldatetime 数据类型。 有什么办法吗?我见过一些人使用 ParseExact,但他们将其与完美的日期格式一起使用,从未像我想的那样从两个字符串创建它。有谁知道如何做到这一点?

最佳答案

你可以试试这个:

string day   = "05";
string month = "11";
string year  = "0001";
DateTime dt  = 
 DateTime.ParseExact(day + "-" + month + "-" + year, "dd-MM-yyyy", CultureInfo.InvariantCulture);

但是年份不能为0。

'0001' 年仅代表第一年。所以你可以说到这个日期已经过了 0 年。

更新

正如下面提到的jimi

smalldatetime goes from 1900-01-01 to 2079-06-06. The OP will have to safe-check this range before converting.

在将字符串解析为 Date 时必须小心,如果您要使用 smalldatetime,您的范围会受到“1900-01-01 到 2079-06-06”的限制,因此您的DateTime 不能有 0001 年。

关于c# - 从 C# 中的两个字符串变量转换为 DateTime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50711679/

相关文章:

c# - 如何将 List<string> 转换为 List 中的逗号分隔引号字符串

javascript - 在具有 Javascript 匹配的字符串中查找插入符号 ^ 字符

Mysql 获取生命周数

javascript - 时间戳到文本

c# - .Net Core Strings.Asc/Mid/Chr/Len 即使在导入 Microsoft.VisualBasic 后也丢失

c# - 查找 "Dead code"

arrays - 将空格插入 char 数组

javascript - 将日期字符串转换为 Date 对象

c# - 递归 linq 和这个?

string - 在 CSV 文件中特定列的 3 个字符后插入空格