如何将像“21Fr”这样的星期和日期字符串添加到DateTime格式中?

时间:2014-10-01 07:14:07

标签: c# asp.net-mvc parsing datetime date-parsing

您好,我正在以“21Fr”格式(一年中的第21周和星期五的第21周)和“06:00”中的时间进行一年中的一天和一周。我想将这2个值加入,并以下面的格式获得输出?任何帮助都会非常值得关注

  

23/05/2014 06:00:00

1 个答案:

答案 0 :(得分:0)

强烈建议您尽可能更改输入格式。但是,这是一种方法:

// parse the input
string input = "21Fr";
// assuming week number is always 2 characters. e.g.: 01, 02, ..., 21, ...
int weeks = int.Parse(input.Substring(0, 2));
// assuming abbreviated day names like this
string[] abbrDayNames = { "Su", "Mo", "Tu", "We","Th", "Fr", "Sa" };
int dayOfWeekValue = Array.IndexOf(abbrDayNames, input.Substring(2));
DayOfWeek dayOfWeek = (DayOfWeek)dayOfWeekValue;

// now let's build the DateTime
// start from first day of year, 6:00 AM
DateTime parsed = new DateTime(DateTime.Now.Year, 1 ,1, 6, 0, 0);
// add first part, weeks
parsed = parsed.AddDays((weeks - 1) * 7);
// reset to first day of week
parsed = parsed.AddDays(-(int)parsed.DayOfWeek);
// then add the second part, day of week
parsed = parsed.AddDays((int)dayOfWeek);

这也假定(基于您的样本输出)第21周意味着您的第21周。