tags:

views:

105

answers:

2

hi..before this i'm using this function to from 6 month date to today date..

dFromYear := AddMonth(dFromDate, -5);
dToYear   := EncodeDate(iYr, iMon, DaysInMonth(iYr, iMon));

but now i want to get date from january until today date...for example if today month is september 2010 so i want to get date from january2010 to september 2010..if today date is may2009 so i want to get from january2009 to may2009..i hope anyone can help me..thanks

+3  A: 

I'm not quite sure what you mean, but if you want to calculate the number of months from January to now there's a function in DateUtils called MonthsBetween that will do it for you.

Like so:

program Project1;

{$APPTYPE CONSOLE}

uses
  SysUtils,DateUtils;

var
  vMonths    : integer;
  vFromDate,
  vToDate    : TDateTime;

begin
  vFromDate := EncodeDate(YearOf(Now),1,1);
  vToDate   := Now;
  vMonths   := DateUtils.MonthsBetween(vFromDate,vToDate);

  writeln(vMonths);
end.
Svein Bringsli
You must be psychic. I would never have guessed that this is what the questionner was after... :)
Marjan Venema
I'm not psychic, but I rely on my magic 8-ball fairly often :-)
Svein Bringsli
Beware. On March 1, that calculation will say that only *one* month has passed. Most years, it will even give that result until 11:24 p.m. on March 2.
Rob Kennedy
+3  A: 

The MonthsBetween function assumes a month is 30.4375 days long, which means it will disagree in many cases where people can calculate the expected answer mentally, and that can be embarrassing. If you want the whole number of months that have passed since January 1 of the current year, you can be more accurate without that function:

function WholeMonthsElapsedThisYear: Integer;
begin
  Result := MonthOf(Date) - 1;
end;

For any date in September, that function will return 8. For any date in January, it will return 0, and it will correctly return 2 on March 1.

Rob Kennedy
+1 for pointing this out. Was gonna do it, but got caught up... :)
Marjan Venema