比如我输入2004-3   (这里没有严格控制用户输入的格式,不排除输入错误的格式)
如何获取2004年3月最后一天的日期?

解决方案 »

  1.   

    下面的函数返回指定日期的所在月的最后一天的日期: 
    function LastDayOfMonth(Dat: TDate): TDate;varD, M, Y : Word;beginDecodeDate(IncMonth(Dat, 1), Y, M, D);Result := EncodeDate(Y, M, 1) - 1;end;
      

  2.   

    function DaysInMonth(ADate:TDateTime):Integer;
    var
      MyMonth,
      MyYear,
      MyDay : Word;
      tmpBool : Boolean;
    begin
      DecodeDate(ADate, MyYear, MyMonth, MyDay);
      tmpBool := IsLeapYear(MyYear);
      case mymonth of
      1,3,5,7,8,10,12 :result:=31;
      4,6,9,11        :result:=30;
      2               :
        begin
          if TmpBool then
            result:=29
          else
            result:=28
        end;
      end;
    end;
      

  3.   

    showmessage(inttostr(daysinmonth(Date)));
      

  4.   

    UnitDateUtilsCategorydatetime routinesDelphi syntax:function EndOfAMonth(const AYear, AMonth: Word): TDateTime;
      

  5.   

    Function GetLastDate(sYM:String):TDateTime;
    begin
      Result:=EncodeDate(StrToInt(Copy(sYM,1,4)),StrToInt(Copy(sYM,6,1))+1,1)-1;
    end;
      

  6.   

    procedure TForm1.Button1Click(Sender: TObject);
    var
        dt:TDateTime;
    begin
        try
            dt:=EndOfAMonth(StrToInt(Copy(Edit1.Text,1,4)),StrToInt(Copy(Edit1.Text,6,2)));
            Label1.Caption:=FormatDateTime('yyyy-mm-dd',dt);
        except
        ///////////
        end;
    end;
      

  7.   

    to  mezw(灵珠子) 
    该函数的输入是一个日期还是包含了时间?
      

  8.   

    i:=DaysInMonth(now);
    i = 当前日期所在月份的总天数
      

  9.   

    原理就是利用incmonth加一月
    然后再减一天,最后encode 就可以了
      

  10.   

    或者用
    Returns the number of days in a specified month of a specified year.UnitDateUtilsCategorydatetime routinesDelphi syntax:function DaysInAMonth(const AYear, AMonth: Word): Word;C++ syntax:extern PACKAGE Word __fastcall DaysInAMonth(const Word AYear, const Word AMonth);DescriptionCall DaysInAMonth to obtain the number of days in the specified month of the specified year.AYear is a year between 1 and 9999 (inclusive).AMonth is a month between 1 and 12 (inclusive).
      

  11.   

    那么我是不是可以这样考虑,
    比如edit1.text为2004-3,我可以设edit.text+'-1'则为改月的第一天(2004-3-1)
    然后转换成为Date格式,再通过i:=DaysInMonth(转换格式后的Date);
    然后就是把2004-3-i字符串转换为Date格式?
    这样可行吗?
    如果可行,如何把String转换成Date格式(手头上没书,所以只能罗嗦问一下)