无法将字符串转换为datetime [英] Can not convert string to datetime

查看:116
本文介绍了无法将字符串转换为datetime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从字符串获取日期时间,我需要的日期时间必须是军事格式(24小时示例下午1:30应该是13:30)或者有PM,AM指示

这个链接没有帮助我

//https://msdn.microsoft.com/en-us/library/5ey6h79d%28v=vs.110%29.aspx



i尝试了这个

i am trying to get datetime from string, the date time i need must either be in military format ( 24 Hour example 1:30 PM should be 13:30 ) or has PM ,AM indication
this link has not helped me
//https://msdn.microsoft.com/en-us/library/5ey6h79d%28v=vs.110%29.aspx

i tried this

System.DateTime dt = new System.DateTime();
dt = Convert.ToDateTime("01/08/2008 4:50:50.42");//<---- error here
MessageBox.Show(dt.ToString());





我尝试过:



DateTime date1 = new DateTime(int.Parse(2009),

int.Parse(8),

int.Parse( 1),

int.Parse(0),

int.Parse(0),

int.Parse (0)

);

i认为不可能在上面的代码中插入AM或PM作为最后一个参数



What I have tried:

DateTime date1 = new DateTime(int.Parse("2009"),
int.Parse("8"),
int.Parse("1"),
int.Parse("0"),
int.Parse("0"),
int.Parse("0")
);
i think it is not possible to insert AM or PM as a last parametr in the above code

推荐答案

什么是错的



whats wrong with

string dateString = "01/01/2008 4:50:50.42"; 
string format = "dd/MM/yyyy h:mm:ss.ff";

DateTime dateTime = DateTime.ParseExact(dateString, format, CultureInfo.InvariantCulture);





?你可以按照这里的说明符 - 'tt'例如是AM / PM ... 自定义日期和时间格式字符串 [ ^ ]


您的代码不会产生我的本地化错误



此代码将在输出中生成AM / PM
Your code does not produce any error with my localisation

This code will produce AM/PM in the output
MessageBox.Show(dt.ToString("dd/MM/yyyy HH:m:s tt"));



但是如果你正在使用日期(特别是如果它们被用于你应该使用明确的日期格式



例如数据库的上下文


But if you are using dates (especially if they are being used in the context of a database) then you should use unambiguous date formats

e.g.

System.DateTime dt = new System.DateTime();
dt = Convert.ToDateTime("2008-08-01 4:50:50.42");
MessageBox.Show(dt.ToString("yyyyMMddTHH:00:00tt"));



产生


which produces

20080801T04:00:00AM


这篇关于无法将字符串转换为datetime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆