简体   繁体   中英

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. So the default value for the time will be applied, Remove .Date then you will get the expected result;

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:

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

What you have to do just remove your ending ".Date" from your code.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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