一个月内第一周展示最优雅的方式是什么?

时间:2010-05-17 11:38:44

标签: c# date html-table

在C#中,我想在日历中显示第一周(在html表中),我想找出最优雅的算法来生成正确的日子。

如果一周的第一天不是星期天,我想显示前一个月的日子(就像你会在常规日历上看到的那样)。因此,作为输入,您有一个当前月份。在这种情况下,梅。我想生成这个:

月:可能

 <table>
 <tr>
   <th>S</th>
   <th>M</th>
   <th>T</th>
   <th>W</th>
   <th>TH</th>
   <th>F</th>
   <th>Sa</th>
 </tr>
 <tr>
   <td>25</td>
   <td>26</td>
   <td>27</td>
   <td>28</td>
   <td>29</td>
   <td>30</td>
   <td>1</td>
 </tr></table>

所以它应该显示这样的东西(忽略对齐)

S | M | T | W | Th | F | Sa |
25 - 26 - 27 - 28 - 29 - 30 - 1

鉴于每个月的开始时间是一周的不同日期,我试图找出一种使用DateTime对象获取此数据值的优雅方法。我看到它在约会时有一个星期日的财产。

我在我的服务器上用C#生成此表以传递给html页面。

5 个答案:

答案 0 :(得分:3)

您可以使用以下代码获取第一周:

public static IEnumerable<DateTime> GetFirstWeek(int year, int month) {
    DateTime firstDay = new DateTime(year, month, 1);
    firstDay = firstDay.AddDays(-(int) firstDay.DayOfWeek);
    for (int i = 0; i < 7; ++i)
        yield return firstDay.AddDays(i);
}

答案 1 :(得分:2)

public static IEnumerable<DateTime> GetFirstWeek(int month, int year)
    {
        var firstDay = new DateTime(year, month, 1);
        var dayOfWeek = firstDay.DayOfWeek;
        var firstWeekDay = firstDay.AddDays(-(int)dayOfWeek);

        for (int i = 0; i < 7; i++)
        {
            yield return firstWeekDay.AddDays(i);
        }
    }

答案 2 :(得分:1)

这应该有效:

DateTime date = new DateTime(year, month, 1);
DayOfWeek firstDay = CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek;
int daysBack = (7 + date.DayOfWeek - firstDay) % 7;

Enumerable.Range(-daysBack, 7)
    .Select(x => date.AddDays(x))
    .ToList()
    .ForEach(d => 
    {
        // a place for html generation
    });

答案 3 :(得分:0)

这是一种简单的方法。

    //Code not tested thoroughly.
    private DateTime[] GetWeek(int month)
    {
        DateTime firstDayofMonth = new DateTime(DateTime.Now.Year, month, 1);
        if (firstDayofMonth.DayOfWeek == DayOfWeek.Sunday)
            return GetWeek(firstDayofMonth);
        else
        {
            DateTime sundayOfPreviousMonth = firstDayofMonth;
            do
            {
                sundayOfPreviousMonth = sundayOfPreviousMonth.AddDays(-1);
            } while (sundayOfPreviousMonth.DayOfWeek != DayOfWeek.Sunday);
            return GetWeek(sundayOfPreviousMonth);
        }
    }

    private DateTime[] GetWeek(DateTime date)
    {
        if (date.DayOfWeek != DayOfWeek.Sunday)
            throw new ArgumentException("Invalid weekday.");
        DateTime[] week = new DateTime[7];
        for (int i = 0; i < week.Length; i++)
        {
            week[i] = date.AddDays(i);
        }
        return week;
    }

答案 4 :(得分:0)

检查此代码:

var days = new[]
{
    "S", "M", "T", "W", "TH", "F", "Sa"
};
var date = DateTime.Parse( "01.05.2010" );
var dayOfWeek = (int)date.DayOfWeek;

for( var i = 0; i < 7; i++ )
{
    Console.WriteLine( days[i] + ": " + date.AddDays( i - dayOfWeek ) );
}

这只是给你一个想法的代码 - 例如你应该使用CultureInfo来解析你的日期。我现在使用任何日期作为输入,但你也可以将它减少到每个月的第一天。