private LetterPostion SameLetterPostion(char letter, string format, int postion) { LetterPostion count = new LetterPostion(); int leftPostion = postion; int rightPostion = postion; while (leftPostion > 0) { leftPostion--; if (format[leftPostion] == letter) { count.LeftCount++; } else { break; } } while (rightPostion < format.Length - 1) { ++rightPostion; if (format[rightPostion] == letter) { count.RightCount++; } else { break; } } return(count); }
public DateTime Format(string format, int chengedPostion, bool isUp, DateTime baseTime) { string timeFormat = format; DateTime time = baseTime; // hh:mm:ss => !h!h!:!m!m!:!s!s! => 9! length= 8 //chengedPostion max= 8 min = 0 if (chengedPostion > timeFormat.Length) { throw new ArgumentOutOfRangeException("chengedPostion"); } if (chengedPostion >= timeFormat.Length - 1) { chengedPostion = timeFormat.Length - 1; } if (chengedPostion < 0) { chengedPostion = 0; } int operand = isUp ? 1 : -1; char positionchar = timeFormat[chengedPostion]; LetterPostion postion = SameLetterPostion(positionchar, timeFormat, chengedPostion); switch (positionchar) { case ':': return(Format(format, chengedPostion - 1, isUp, baseTime)); case '-': return(Format(format, chengedPostion - 1, isUp, baseTime)); case 'h': return(time.AddHours(operand)); case 'm': operand = (int)Math.Pow(10, postion.RightCount) * operand; return(time.AddMinutes(operand)); case 's': operand = (int)Math.Pow(10, postion.RightCount) * operand; return(time.AddSeconds(operand)); case 'd': return(time.AddDays(operand)); case 'M': return(time.AddMonths(operand)); case 'y': operand = (int)Math.Pow(10, postion.RightCount) * operand; if (time.Year + operand < 1 || time.Year + operand > 9999) { return(time); } return(time.AddYears(operand)); default: throw new NotImplementedException(); } }