0

I want to execute code if the now time is over a certain time given in a string:

var
  Time,mynowtime:TTime;
begin
  mynowtime := ('24:00:00');
  Time := Frac(Now);

  if Time > mynowtime then
  begin
    ShowMessage(TimeToStr(Time));
  end;

It gives me an error:

'24:00:00' is not a valid date and time.

Tom Brunberg
  • 20,312
  • 8
  • 37
  • 54
Kan
  • 111
  • 1
  • 10
  • 1
    `mynowtime := ('24:00:00');` is a string assignment, not a TTime, and a string assignment to a `TTime` variable isn't possible. Also, 24 hours isn't time; it's a day. There is no time, because it's a full 24 hours with no minutes or seconds, and the TTime value would be zero (the TDateTime value would be `1.0`, with the `TTime` value = `0.0`. It appears you're trying to match midnight exactly, to the second, and you're never going to do that with any reliability. It would be better if you asked about what you're really trying to accomplish. – Ken White Dec 21 '17 at 05:00
  • 1
    Use `StrToTime()` or `EncodeTime()` to create the `TTime`. Use the RTL's `Time()` function, or at least `TimeOf(Now)`, instead of `Frac(Now) ` – Remy Lebeau Dec 21 '17 at 05:35
  • 2
    Compare time portion would have poss dup: https://stackoverflow.com/q/23990987/224704 However, clearly the error you're getting has nothing to do with ***comparing***. So the more likely duplicate is: https://stackoverflow.com/q/23420818/224704 Google the following: `site:stackoverflow.com delphi string to time` and you'll find many more candidate duplicates. As it stands, I'm voting to close because your question is unclear. – Disillusioned Dec 21 '17 at 06:08

1 Answers1

0

as Ken White and Remy Lebeau said in Their comments, you can do it like this;

if CompareTime(Time(), EncodeTime(23, 0, 0, 0)) > 0 then
  ShowMessage('it''s late');

if the time value is coming from an external source;

var
FmtStngs: TFormatSettings;

Begin
  GetLocaleFormatSettings( GetThreadLocale, FmtStngs );
  // set format settings, for more info have a look at the link below

  if CompareTime(Time(), StrToTime('23:00:00', FmtStngs)) > 0 then
    ShowMessage('it''s late');
End;

link

sddk
  • 1,115
  • 1
  • 10
  • 20
  • 1
    Unless the time string is coming from an external source, it is wasted overhead to use `StrToTime()` with a string literal. Use `EncodeTime()` instead: `t1 := EncodeTime(23, 0, 0, 0);` And do use `Time()` instead of `TimeOf(Now())`: `t2 := Time;` Put together: `if CompareTime(Time, EncodeTime(23, 0, 0, 0)) > 0 then` – Remy Lebeau Dec 21 '17 at 06:52
  • 1
    when using `StrToTime()`, you should pass it a `TFormatSettings` describing the format of the string, otherwise the user's locale settings are used, which may or may not match, depending on where the string is coming from. – Remy Lebeau Dec 21 '17 at 08:05