如何将诸如2009-05-08 14:40:52,531这样的字符串转换为DateTime?
当前回答
String now = DateTime.Now.ToString("YYYY-MM-DD HH:MI:SS");//make it datetime
DateTime.Parse(now);
这个给了你
2019-08-17 11:14:49.000
其他回答
似乎没有人实现过扩展方法。通过@CMS的回答:
工作和改进的完整源代码示例在这里:Gist Link
namespace ExtensionMethods {
using System;
using System.Globalization;
public static class DateTimeExtensions {
public static DateTime ToDateTime(this string s,
string format = "ddMMyyyy", string cultureString = "tr-TR") {
try {
var r = DateTime.ParseExact(
s: s,
format: format,
provider: CultureInfo.GetCultureInfo(cultureString));
return r;
} catch (FormatException) {
throw;
} catch (CultureNotFoundException) {
throw; // Given Culture is not supported culture
}
}
public static DateTime ToDateTime(this string s,
string format, CultureInfo culture) {
try {
var r = DateTime.ParseExact(s: s, format: format,
provider: culture);
return r;
} catch (FormatException) {
throw;
} catch (CultureNotFoundException) {
throw; // Given Culture is not supported culture
}
}
}
}
namespace SO {
using ExtensionMethods;
using System;
using System.Globalization;
class Program {
static void Main(string[] args) {
var mydate = "29021996";
var date = mydate.ToDateTime(format: "ddMMyyyy"); // {29.02.1996 00:00:00}
mydate = "2016 3";
date = mydate.ToDateTime("yyyy M"); // {01.03.2016 00:00:00}
mydate = "2016 12";
date = mydate.ToDateTime("yyyy d"); // {12.01.2016 00:00:00}
mydate = "2016/31/05 13:33";
date = mydate.ToDateTime("yyyy/d/M HH:mm"); // {31.05.2016 13:33:00}
mydate = "2016/31 Ocak";
date = mydate.ToDateTime("yyyy/d MMMM"); // {31.01.2016 00:00:00}
mydate = "2016/31 January";
date = mydate.ToDateTime("yyyy/d MMMM", cultureString: "en-US");
// {31.01.2016 00:00:00}
mydate = "11/شعبان/1437";
date = mydate.ToDateTime(
culture: CultureInfo.GetCultureInfo("ar-SA"),
format: "dd/MMMM/yyyy");
// Weird :) I supposed dd/yyyy/MMMM but that did not work !?$^&*
System.Diagnostics.Debug.Assert(
date.Equals(new DateTime(year: 2016, month: 5, day: 18)));
}
}
}
你想快点吗?
假设您有一个格式为yyMMdd的日期。
我发现转换它的最快方法是:
var d = new DateTime(
(s[0] - '0') * 10 + s[1] - '0' + 2000,
(s[2] - '0') * 10 + s[3] - '0',
(s[4] - '0') * 10 + s[5] - '0')
只需根据您选择的日期格式选择索引。如果你需要速度,你可能不介意函数的“非泛型”方式。
此方法所需时间约为以下操作所需时间的10%:
var d = DateTime.ParseExact(s, "yyMMdd", System.Globalization.CultureInfo.InvariantCulture);
使用DateTime.Parse(字符串):
DateTime dateTime = DateTime.Parse(dateTimeStr);
将此代码放入静态类>公共静态类ClassName{}
public static DateTime ToDateTime(this string datetime, char dateSpliter = '-', char timeSpliter = ':', char millisecondSpliter = ',')
{
try
{
datetime = datetime.Trim();
datetime = datetime.Replace(" ", " ");
string[] body = datetime.Split(' ');
string[] date = body[0].Split(dateSpliter);
int year = date[0].ToInt();
int month = date[1].ToInt();
int day = date[2].ToInt();
int hour = 0, minute = 0, second = 0, millisecond = 0;
if (body.Length == 2)
{
string[] tpart = body[1].Split(millisecondSpliter);
string[] time = tpart[0].Split(timeSpliter);
hour = time[0].ToInt();
minute = time[1].ToInt();
if (time.Length == 3) second = time[2].ToInt();
if (tpart.Length == 2) millisecond = tpart[1].ToInt();
}
return new DateTime(year, month, day, hour, minute, second, millisecond);
}
catch
{
return new DateTime();
}
}
这样,你就可以使用
string datetime = "2009-05-08 14:40:52,531";
DateTime dt0 = datetime.TToDateTime();
DateTime dt1 = "2009-05-08 14:40:52,531".ToDateTime();
DateTime dt5 = "2009-05-08".ToDateTime();
DateTime dt2 = "2009/05/08 14:40:52".ToDateTime('/');
DateTime dt3 = "2009/05/08 14.40".ToDateTime('/', '.');
DateTime dt4 = "2009-05-08 14:40-531".ToDateTime('-', ':', '-');
我只是找到了一个优雅的方法:
Convert.ChangeType("2020-12-31", typeof(DateTime));
Convert.ChangeType("2020/12/31", typeof(DateTime));
Convert.ChangeType("2020-01-01 16:00:30", typeof(DateTime));
Convert.ChangeType("2020/12/31 16:00:30", typeof(DateTime), System.Globalization.CultureInfo.GetCultureInfo("en-GB"));
Convert.ChangeType("11/شعبان/1437", typeof(DateTime), System.Globalization.CultureInfo.GetCultureInfo("ar-SA"));
Convert.ChangeType("2020-02-11T16:54:51.466+03:00", typeof(DateTime)); // format: "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffzzz"
推荐文章
- 远程主机强制关闭现有连接
- 如何选择记录从过去24小时使用SQL?
- 为什么ReSharper想要使用'var'的一切?
- 如何检查一个对象是否为空?
- 为什么要删除不必要的c#使用指令?
- 使用Pandas为字符串列中的每个值添加字符串前缀
- 我如何能匹配一个字符串与正则表达式在Bash?
- 为什么使用HttpClient进行同步连接
- 尝试模拟datetime.date.today(),但不工作
- 什么是MvcHtmlString,什么时候我应该使用它?
- 我怎么能找到一个列表<>的最后一个元素?
- 如何隐藏关闭按钮在WPF窗口?
- 确定文本文件中的行数
- 如何测试一个字符串是否包含列表中的一个子字符串,在熊猫?
- 生成错误:必须向系统添加引用。运行时