我爲自己工作,我是一名自僱職業編碼人員,因此我沒有代碼審查的豪華感或根據同行編程進行改進的能力。我將以此作爲練習,以查看StackOverflow社區是否可以幫助檢查我寫的一個簡單方法;重構速度:轉換爲日期
internal static DateTime CONVERT_To_DateTime(int binDate)
{
// 3/10/2008 = 1822556159
// 2/10/2008 = 1822523391
// 1/10/2008 = 1822490623
// 30/09/2008 = 1822392319
// 29/09/2008 = 1822359551
// September 30th 2008
// 1822392319 = 0x6c9f7fff
// 0x6c = 108 = 2008 (based on 1900 start date)
// 0x9 = 9 = September
// 0xf7fff - take top 5 bits = 0x1e = 30
// October 1st 2008
// 1822490623 = 0x6ca0ffff
// 0 x6c = 108 = 2008
// 0 xa = 10 = October
// 0x0ffff - take top 5 bits = 0x01 = 1
// OR using Binary (used by this function)
// a = 1822556159 (3/10/2008)
// 1101100 1010 00011 111111111111111
// b = 1822523391 (2/10/2008)
// 1101100 1010 00010 111111111111111
// c = 1822490623 (1/10/2008)
// 1101100 1010 00001 111111111111111
// D = 1822392319 (30/09/2008)
// 1101100 1001 11110 111111111111111
// Excess 111111 are probably used for time/seconds which
// we do not care for at the current time
var BaseYear = 1900;
// Dump the long date to binary
var strBinary = Convert.ToString(binDate);
// Calculate the year
var strBYear = strBinary.Substring(0, 7);
var iYear = Convert.ToInt32(strBYear, 2) + BaseYear;
// Calculate the month
var strBMonth = strBinary.Substring(7, 4);
var iMonth = Convert.ToInt32(strBMonth, 2);
// Calculate the day
var strBDay = strBinary.Substring(11, 5);
var iDay = Convert.ToInt32(strBDay, 2);
// ensure that month and day have two digits
var strDay = iDay < 10 ? "0" + iDay : iDay.ToString();
var strMonth = iMonth < 10 ? "0" + iMonth : iMonth.ToString();
// Build the final date
var convertedDate = iYear + strMonth + strDay;
return DateTime.ParseExact(convertedDate, "yyyyMMdd", null);
}
這是一種採用數字表示日期並將其轉換爲DateTime數據類型的方法。我希望對方法進行審查,以實現儘可能快的執行時間,因爲它是在循環內執行的。
對這個方法的任何評論都很讚賞,因爲這對我來說是一個練習。我期待着一些迴應。
您應該總是用編程語言來標記這樣的問題,以幫助人們找到它。 – unwind 2010-02-03 14:54:00
使用位掩碼和位移方法可以更快地執行二進制操作 – tooleb 2010-02-03 15:02:27
僅供參考,省略二進制數字中的前導0可能會讓其他開發人員感到困惑。期望全部32位被表示是公平的。 – 2010-02-03 15:30:36