5

How to get current time in milliseconds? I know to use Now, but I need to get the time in milliseconds.

var
  today : TDateTime;
begin
  today := Now;
14
  • 3
    People below are guessing, because your question is not clear. I can tell you it's today, 9AM. Now, express me that moment in milliseconds.
    – TLama
    Apr 22, 2015 at 7:51
  • Your request is imprecise. Milliseconds with respect to what epoch? Apr 22, 2015 at 8:01
  • 4
    Well, then it sounds you are looking for a way to calculate number of milliseconds between the time when you do the request and the time when the response arrives. For that is the MilliSecondsBetween function. But if you don't need to rely on TDateTime type, e.g. if that timestamp is not a part of the response content, you can simply use TStopWatch in recent versions of Delphi, or subtract values obtained by GetTickCount calls, for example.
    – TLama
    Apr 22, 2015 at 8:12
  • 1
    @TLama I agree. But it is something that one should be conscious of at least Apr 22, 2015 at 9:09
  • 1
    To avoid the overflow issue, you can use GetTickCount64() instead. Apr 22, 2015 at 17:36

4 Answers 4

26
DateUtils.MilliSecondsBetween(Now, 0);
6

Use the DateUtils MilliSecondOfTheDay:

ms := MillisecondOfTheDay(Now);

Returns the number of milliseconds between a specified TDateTime value and the beginning of the same day.

Should you want the milliseconds from another time frame, there are other similar functions like: MilliSecondOfTheYear, MilliSecondsBetween, etc.

1

A TDateTime is a double where 1 is a day. The SecsPerDay constant declared in SysUtils represents the number of seconds in a day, so to get Now in milliseconds:

todayInMilliseconds := Now * SecsPerDay * 1000.0;
1
  • Not a good idea. Not every day has the same count of seconds. For example the day, on which the clock is changed to daylight saving time, contains 1 hour less. And constant SecsPerDay will be not valid in this case. Feb 3, 2022 at 15:36
1

DecodeDateTime will take a TDateTime and be able to split it up into Year, Month, Day, Hour Minute Second and Millisecond.

See http://www.delphibasics.co.uk/RTL.asp?Name=DecodeDateTime for more info.

Once you have the individual numbers, you can use math to calculate the current millisecond count past midnight.

Var
  myDate: TDateTime;
  myYear, myMonth, myDay: Word;
  myHour, myMin, mySec, myMilli: Word;

begin
  myDate := Now;
  DecodeDateTime(myDate, myYear, myMonth, myDay, myHour, myMin, mySec, myMilli);
  ShowMessage('Number of milliseconds past midnight = ' + IntToStr(myMilli + (mySec * 1000) + (myMin * 60 * 1000) + (myHour * 60 * 60 * 1000)));
end;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.