private string FormatDate0(DateTime dateTime)
{
return dateTime.AddYears(-1911).ToString("yyy/MM/dd");
}
以今天為例,結果是 104/12/09,看來沒問題?但試試 FormatDate0(new Date(2016, 2, 29)) => 105/02/28,知道不行了吧?改進如下:
private string FormatDate1(DateTime dateTime)
{
string returnValue = null;
Calendar taiwanCalendar = new TaiwanCalendar();
int year = taiwanCalendar.GetYear(dateTime);
int month = taiwanCalendar.GetMonth(dateTime);
int day = taiwanCalendar.GetDayOfMonth(dateTime);
returnValue = String.Format("{0:000}/{1:00}/{2:00}", year, month, day);
return returnValue;
}
[SecurityPermission(SecurityAction.Assert, ControlThread = true)]
private string FormatDate2(DateTime dateTime)
{
string returnValue = null;
CultureInfo taiwanCulture = new CultureInfo("zh-TW");
DateTimeFormatInfo formatInfo = taiwanCulture.DateTimeFormat;
Calendar taiwanCalendar = new TaiwanCalendar();
formatInfo.Calendar = taiwanCalendar;
Thread currentThread = Thread.CurrentThread;
currentThread.CurrentCulture = taiwanCulture;
returnValue = dateTime.ToString("yyy/MM/dd");
return returnValue;
}
...
// bugfix begin
//returnValue = dateTime.ToString("yyy/MM/dd");
int year = taiwanCalendar.GetYear(dateTime);
returnValue = String.Format("{0:000}", year);
returnValue += dateTime.ToString("/MM/dd");
// bugfix end
return returnValue;
}
沒有留言:
張貼留言