toitware / public

Issue tracking for the Toit IoT platform, the Toit language, and the Toit APIs.
9 stars 0 forks source link

Time.now could have functions for different timezones #21

Open hippyaki opened 3 years ago

hippyaki commented 3 years ago

Currently, Time.now.local converts the UTC to CEST which is local for Denmark only. For people from other countries, to use the toit script, an inbuild timezone function could do good.

I wrote a code to convert from UTC to IST (Indian Standard Time).

main:
  time := Time.now.utc

  timeh := time.h + 5
  timem := time.m + 30
  timeday := time.day

  if timem > 60:
    timeh = timeh + 1
    timem = timem - 60

    if timeh >= 24:
      timeday = timeday + 1
      timeh = timeh - 24

  print "Time: $(%02d timeh):$(%02d timem)"
  print "Date: $(%04d time.year)-$(%02d time.month)-$(%02d time.day)"

I have only started with toit, hoping to learn and make great projects out of it.

floitsch commented 3 years ago

In the meantime there is a work-around:

import core.time_impl show set_tz_
main:
  // Valid TZ values can be easily obtained by looking at the last line of the
  //  zoneinfo files on Linux machines:
  // ```
  // tail -n1 /usr/share/zoneinfo/Europe/Copenhagen
  // ```
  // Alternatively, the following link seems to have some common timezones:
  //    https://sites.google.com/a/usapiens.com/opnode/time-zones
  set_tz_ "CET-1CEST,M3.5.0,M10.5.0/3"
  print Time.now.local

This hack uses a private function and is thus not guaranteed to continue to work, but it updates the internal TZ settings to the timezone of your choice.

Note that this call affects all apps on the device. Also: avoid changing the TZ too often. There is a known memory-leak if the variable is changed too often.

hippyaki commented 3 years ago

As discussed on slack, I'll put down the other workarounds for Asia/Kolkata i.e. IST +5:30 as an example to update the timezone locally on device.

Example - 1

import core.time_impl show set_tz_
main:
  set_tz_ "IST-5:30"
  print Time.now.local

Example - 2

main:
  print (Time.now + (Duration --h=5 --m=30)).utc

This might help for anyone else with the same query.