2014-02-22 46 views
6

如何在C#中從day of year獲得date如何從年初獲取日期

我有這樣的代碼:

int a = 53; // This is the day of year value, that I got previously 
string b = Convert.ToDateTime(a).ToString(); // Trying to get the date 

我需要得到的價值22.2.2014。但這不起作用,我該怎麼辦?提前致謝。

+0

你可能需要使用TimeSpan.FromDays添加a到( x):http://msdn.microsoft.com/en-us/library/system.timespan.fromdays(v=vs.110).aspx然後使用該值將其轉換爲DateTime。 –

+0

謝謝你的評論。 –

回答

11
int a = 53; 
int year = DateTime.Now.Year; //Or any year you want 
DateTime theDate = new DateTime(year, 1, 1).AddDays(a - 1); 
string b = theDate.ToString("d.M.yyyy"); // The date in requested format 
+1

非常感謝你,這工作完美,只需要更正toString ToString –

1
int a = 53; 
var dt = new DateTime(DateTime.Now.Year, 1, 1).AddDays(a - 1); 
string b = dt.ToString(); 
+0

非常感謝!有效。 –

3

假設您想當年?

int a = 53; 
DateTime date = new DateTime(DateTime.Now.Year, 1,1).AddDays(a -1); 
+0

謝謝你的回答。 –

相關問題