2016-06-28 226 views
0

我有以下幾點:C#日期格式問題

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

此打印出無小時和分鐘的日期。我如何使它工作並顯示時間?

回答

0

,你所要做的只是從你的代碼中刪除你的結局「.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(); 
1

要調用.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); 

會產生:

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

通知上月底

2

缺乏.Date的使用.Date您只從結果的DateTime對象中選擇日期部分。因此,時間的默認值將被應用,刪除.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); 

Example會告訴你區別