2014-04-23 32 views
0

我想以12小时格式输出日期时间。它适用于某些然后中断。在C#中格式化日期时间#

代码:

while (myReader.Read()) 
{ 
    Console.WriteLine("Date Before formatting = " + myReader["Date"].ToString()); 
    DateTime dt = DateTime.ParseExact(myReader["Date"].ToString(), "yyyy/MM/dd hh:mm:ss", CultureInfo.InvariantCulture); 


    string format = "MM/dd/yyyy hh:mm:ss tt"; 
    Console.WriteLine(myReader["RxNumber"].ToString() + "\t\t" + dt.ToString(format)); 
} 

输出:

连接打开

日期格式= 2013年12月26日11时26分08秒

  12/26/2013 11:26:08 AM 

日期格式化之前之前= 2013/12/26 09:02:01

12345 2013年12月26日上午09时02分01秒

日期之前格式= 2013年12月26日9时04分29秒

123456 2013年12月26日上午09时04分29秒

日期格式= 2013年10月28日十点19分26秒

  10/28/2013 10:19:26 AM 

日期之前格式= 2014年2月14日12时25分57秒

7000006 2014年2月14日12:25之前:57 AM

日期之前格式= 2014年2月14日13点20分18秒

System.FormatException:字符串未被识别为有效的DateTime。 在System.DateTimeParse.ParseExact(字符串s字符串格式,的DateTimeFormatInfo dtfi,DateTimeStyles样式) 在System.DateTime.ParseExact(字符串s字符串格式,提供者的IFormatProvider) 在test.Program.Main(字串[] args)在c:\ Users \ Admin \ Desktop \用于测试test608 \ test \ test \ Program.cs的软件中:第33行 ☺按任意键继续。 。 。

+0

你可以给我们一个引发异常的字符串值的例子吗? – Bill

+0

我已更新我的问题以获得更好的输出。 – user3562751

+0

您的输出与您的代码不符。我倾向于猜测迈克尔的答案是对的。 –

回答

2

您的问题是数据库正在以24小时格式存储这些值,并且您将它们解析为DateTime作为12小时格式;用这个代替:

DateTime dt = DateTime.ParseExact(
    myReader["Date"].ToString(), 
    "yyyy/MM/dd HH:mm:ss", 
    CultureInfo.InvariantCulture); 

一旦从数据库中正确解析日期,输出为12小时格式就可以了。

+0

是的!非常感谢! – user3562751

1

在军事(24小时)使用HHhh用于标准12小时的时间。

+1

感谢您的帮助! – user3562751