Setting the Time

Материал из Поле цифровой дидактики

With Scratch 3.0's time reporter capabilities, displaying the time or creating a string of the current time is possible. However, using the (current [hour v]) block displays a 24-hour clock, which means it uses Шаблон:Wp instead of using ‘a.m.’ and ‘p.m.’ There are also some other problems. This tutorial shows how to properly display the time to one's liking as an alternative to joining the basic time capabilities provided by the current [ v] block.

Programming

One of the issues with the current () block is that minutes and seconds are not zero-padded, meaning they do not have a "0" before single-digit values. For example, time may be displayed realistically as:

1:04:07 p.m.

Meaning it is 1 hour, 4 minutes, and 7 seconds past 12:00 p.m. However, joining the strings together, Scratch would normally display the time as:

13:4:7

To work around this, variables can be used to designate the realistically correct value for each time unit, and then they can be joined together as a string. To fix the 24-hour issue, one can add -12 to the hour if it reaches a certain time. For the following script, assume:

  • (hour) is the variable used to display the current hour
  • (minute) is the variable used to display the current minute
  • (second) is the variable used to display the current second
  • (half) is the variable used to display if the time is before or after 12:00 p.m.
  • (time) is the variable used to display the united time

In the script below, for example, if you do not want to include "seconds" or any other time unit, the instances of it as well as related blocks must be removed:

when gf clicked
forever
if <<(current [hour v]) > (12)> or <(current [hour v]) = [0]>> then //if in the afternoon to midnight, or up to an hour past midnight
set [hour v] to ([abs v] of ((current [hour v]) - (12))) //the absolute value is needed in case the hour equals "0"
else
set [hour v] to (current [hour v])
end
if <(current [minute v]) < (10)> then //if a single digit
set [minute v] to (join [0] (current [minute v]))
else
set [minute v] to (current [minute v])
end
if <(current [second v]) < (10)> then //if a single digit
set [second v] to (join [0] (current [second v]))
else
set [second v] to (current [second v])
end
if <(current [hour v]) < (12)> then //if before afternoon but after midnight
set [half v] to [a.m.]
else
set [half v] to [p.m.]
end
set [time v] to (join (join (join (join (join (join (hour) [:]) (minute)) [:]) (second)) [ ]) (half)) //there is a space after "second"

See Also

ja:時刻を整形する