/// <summary> /// 「DateTime」轉「民國日期時間數字字串」 /// 例:DateTime --> 105/02/16 或 DateTime --> 1050216 或 DateTime --> 1050216125225 /// </summary> /// <param name="dateTime">DateTime</param> /// <param name="format">轉換格式(與DateTime.ToString方法相同)</param> /// <returns>民國日期時間數字字串</returns> public static string DateTimeToTWDateTimeNum(DateTime dateTime, string format) { //取得年份的Format string yearPattern = @"([yY]+)"; Match result = Regex.Match(format, yearPattern); //取得非年份的Format string notYearPattern = @"([^yY]+)"; Match otherResult = Regex.Match(format, notYearPattern); //取得民國年 int year = new TaiwanCalendar().GetYear(dateTime); //把y或Y取代成0 (ToString用法,以0取代預留位置) string yearFormat = result.Value.Replace("y", "Y").Replace("Y", "0"); //回傳格式 return(year.ToString(yearFormat) + dateTime.ToString(otherResult.Value)); }
public static void Main() { // Create an instance of the calendar. TaiwanCalendar myCal = new TaiwanCalendar(); Console.WriteLine(myCal.ToString()); // Create an instance of the GregorianCalendar. GregorianCalendar myGre = new GregorianCalendar(); // Display the MinValue and its equivalent in the GregorianCalendar. DateTime myMin = myCal.MinSupportedDateTime; Console.Write("MinSupportedDateTime: {0:D2}/{1:D2}/{2:D4}", myCal.GetMonth(myMin), myCal.GetDayOfMonth(myMin), myCal.GetYear(myMin)); Console.WriteLine(" (in Gregorian, {0:D2}/{1:D2}/{2:D4})", myGre.GetMonth(myMin), myGre.GetDayOfMonth(myMin), myGre.GetYear(myMin)); // Display the MaxValue and its equivalent in the GregorianCalendar. DateTime myMax = myCal.MaxSupportedDateTime; Console.Write("MaxSupportedDateTime: {0:D2}/{1:D2}/{2:D4}", myCal.GetMonth(myMax), myCal.GetDayOfMonth(myMax), myCal.GetYear(myMax)); Console.WriteLine(" (in Gregorian, {0:D2}/{1:D2}/{2:D4})", myGre.GetMonth(myMax), myGre.GetDayOfMonth(myMax), myGre.GetYear(myMax)); }