Reputation: 1080
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;
Upvotes: 6
Views: 41259
Reputation: 61378
"Date/time in milliseconds" begs the question - milliseconds since when? A common starting point is Jan 1, 1970 (also known as UNIX epoch). For that, use DateTimeToUnix(Now)
from the DateUtils
module.
If this is for taking intervals (i. e. the absolute date/time it not important), there is also a Windows API function GetTickCount()
. It returns milliseconds since the system startup, wraps around at about 49 days.
Upvotes: 0
Reputation: 34909
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.
Upvotes: 6
Reputation: 684
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;
Upvotes: 1
Reputation: 4318
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;
Upvotes: 1