简体   繁体   English

C#日期格式问题

[英]C# Date formatting issue

I have the following: 我有以下内容:

string QDI_DATE_FORMAT = "yyyy-MM-ddTHH:mm:00.0000000K";            

string from = "2016-06-20T16:20:00.0000000-04:00";
string to =   "2016-06-21T16:21:00.0000000-04:00";

DateTime fromDate = DateTime.ParseExact(from, QDI_DATE_FORMAT, CultureInfo.InvariantCulture, DateTimeStyles.None).Date;
DateTime toDate =   DateTime.ParseExact(to, QDI_DATE_FORMAT, CultureInfo.InvariantCulture, DateTimeStyles.None).Date;

Console.WriteLine(fromDate);
Console.WriteLine(toDate);

This prints out the Date without the hour and minutes. 这会打印出不带小时和分钟的日期。 How do I make it work and show the time? 我如何使其工作并显示时间?

By using .Date you are selecting the date part only from the resulted DateTime object. 通过使用.Date您仅从结果DateTime对象中选择日期部分。 So the default value for the time will be applied, Remove .Date then you will get the expected result; 因此,将应用时间的默认值.Date您将获得预期的结果;

DateTime fromDate = DateTime.ParseExact(from, QDI_DATE_FORMAT, CultureInfo.InvariantCulture, DateTimeStyles.None);
DateTime toDate =   DateTime.ParseExact(to, QDI_DATE_FORMAT, CultureInfo.InvariantCulture, DateTimeStyles.None);

This Example will show you the difference 这个例子将告诉你区别

You are calling .date which is selecting just the date part: 您正在调用.date,它仅选择日期部分:

string from = "2016-06-20T16:20:00.0000000-04:00";
DateTime fromDateTime = DateTime.ParseExact(from, QDI_DATE_FORMAT, CultureInfo.InvariantCulture, DateTimeStyles.None);
DateTime toDateTime =   DateTime.ParseExact(to, QDI_DATE_FORMAT, CultureInfo.InvariantCulture, DateTimeStyles.None);

Will produce: 将产生:

> 6/20/2016 8:20:00 PM 
> 6/21/2016 8:21:00 PM

Notice the lack of .Date on the end 注意最后缺少.Date

What you have to do just remove your ending ".Date" from your code. 您所要做的只是从代码中删除结尾的“ .Date”。

string QDI_DATE_FORMAT = "yyyy-MM-ddTHH:mm:00.0000000K";

string from = "2016-06-20T16:20:00.0000000-04:00";
string to = "2016-06-21T16:21:00.0000000-04:00";

DateTime fromDate = DateTime.ParseExact(from, QDI_DATE_FORMAT, CultureInfo.InvariantCulture, DateTimeStyles.None);
DateTime toDate = DateTime.ParseExact(to, QDI_DATE_FORMAT, CultureInfo.InvariantCulture, DateTimeStyles.None);

Console.WriteLine(fromDate);
Console.WriteLine(toDate);

Console.ReadLine();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM