如何根据同月的日期查找一个月中某一天的第5天或结束日期

时间:2015-12-23 11:24:48

标签: c# datetime dayofweek

我一直试图找到一个月中第一周的第5周日期,例如第5周的星期一,第5周的星期二,星期三......依此类推,根据同月的日期。该日期可能属于同月的任何一周。 我试过像

DateTime MonthEventDate=05/01/2016; //Date format in dd/MM/yyyy format

DayOfWeek EventDay="Sunday"; //For Example i want to find 5th Sunday in January Month, but days too will change everytime based on user selection

string SelectedWeek="5"; //Here i'm getting the week in which i need to find the given date i.e, 5th Monday or Tuesday & so on  
if (SelectedWeek == "5")
{
    //Here i tried to add number of days to my initial day to find 5th day date, but every time its returning next month value 
    MonthEventDate = MonthEventDate.AddDays((EventDay < MonthEventDate.DayOfWeek ? 31 : 28) + EventDay - MonthEventDate.DayOfWeek);
}

我知道逻辑是错误的,但我希望得到一周中第5天的日期,如果那天不存在,则返回0.寻找一些指导 注意:这里的月份将根据用户输入进行更改,因此如何返回第五天的日期,如果它在给定的月份中存在

4 个答案:

答案 0 :(得分:2)

这应该给你第5天(如果有的话)......

holder.clean.setOnTouchListener(new OnTouchListener() {

                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        // TODO Auto-generated method stub
                        index = (Integer)v.getTag();
                        //  Log.i("SYNC", "camera"+String.valueOf(index));
                            Toast.makeText(getApplicationContext(), String.valueOf(index), Toast.LENGTH_SHORT).show();
                        v.setBackgroundColor(Color.parseColor("#1C6614"));
                        v.getParent().findViewById(R.id.dirty_view_id).setBackgroundColor(Color.parseColor("#8A8787"));
                        v.getParent().findViewById(R.id.na_view_id).setBackgroundColor(Color.parseColor("#8A8787"));
                        v.getParent().findViewById(R.id.dc_view_id).setBackgroundColor(Color.parseColor("#8A8787"));
                        Status = "1";

                        index = (Integer)v.getTag();
                        Log.i("SYNC", String.valueOf(index));

                        String timeStamp = new SimpleDateFormat(
                                "MM/dd/yyyy hh:mm:ss a").format(new Date());

                        db.updateInspectionDetails(inspection_id, user_id,
                                location_inspection_array.get(position)
                                        .getComponentid(), subclient_id, client_id,
                                Status, images_path_string, timeStamp);

                        return false;
                    }
                });

答案 1 :(得分:0)

扩展@SonerGönül的答案。在输入中,您输入所需的星期几,所需的月份和所需的年份。在输出时,您将获得第五周中同一天的日期,或null

    public DateTime? FifthDay(DayOfWeek dayOfWeek, byte monthNum, int year)
    {
        if (monthNum > 12 || monthNum < 1)
        {
            throw new Exception("Month value should be between 1 and 12");
        }

        var searchDate = new DateTime(year, monthNum, 1);
        var weekDay = searchDate.DayOfWeek;

        if (weekDay == dayOfWeek)
        {
            searchDate = searchDate.AddDays(28);
        }

        for (DateTime d = searchDate; d < d.AddDays(7); d = d.AddDays(1))
        {
            if (d.DayOfWeek == dayOfWeek)
            {
                searchDate = searchDate.AddDays(28);
                break;
            }
        }

        if (searchDate.Month == monthNum)
            return searchDate;

        return null;
    }

答案 2 :(得分:0)

您可以使用这样的简单数学(不包括验证)

static DateTime? FindDate(int year, int month, DayOfWeek dayOfWeek, int weekOfMonth = 5)
{
    var baseDate = new DateTime(year, month, 1);
    int firstDateOffset = ((int)dayOfWeek - (int)baseDate.DayOfWeek + 7) % 7;
    var date = baseDate.AddDays(firstDateOffset + 7 * (weekOfMonth - 1));
    return date.Month == month ? date : (DateTime?)null; 
}

我认为代码是自我解释的。可能需要解释的唯一技巧是行

    int firstDateOffset = ((int)dayOfWeek - (int)baseDate.DayOfWeek + 7) % 7;

处理这种情况,比如说月份从星期五开始,你要求周一,并且相当于

int firstDateOffset = (int)dayOfWeek - (int)baseDate.DayOfWeek;
if (firstDateOffset < 0) firstDateOffset += 7;

示例中的用法

var monthEventDate = FindDate(2016, 1, DayOfWeek.Sunday, 5);

答案 3 :(得分:0)

您可以参考此演示代码

  int requiredDay = 5; //Day number i.e 0-6(Sunday to SaturDay)
  DateTime day = new DateTime(2016, 1, 1); //Month,year,Date
  if (DateTime.DaysInMonth(day.Year, day.Month) > 28)
  {
      //Get the first day name of the month
       int firstMonthDay = (int)day.DayOfWeek;

       int offset=0;

      //Number of days from the first day for the required day
      if (firstMonthDay <= requiredDay)
          offset = requiredDay - firstMonthDay;
     else
        offset = 7 - firstMonthDay + requiredDay;
//
    DateTime firstoccurence = day.AddDays((double)offset);
    DateTime fifthOccurence = firstoccurence.AddDays(28);
    if (fifthOccurence.Month == firstoccurence.Month)
          MessageBox.Show(fifthOccurence.ToString());
    else
         MessageBox.Show("No 5th Occurence for this day");
   }