Charfeddine Mohamed Ali
Charfeddine Mohamed Ali

Reputation: 1106

How can I set the default timezone in Lua?

can i set default timezone in Lua just like in PHP

date_default_timezone_set("Europe/London");
$Year = date('y');
$Month = date('m');
$Day = date('d');
$Hour = date('H');
$Minute = date('i'); 

Upvotes: 0

Views: 240

Answers (1)

koyaanisqatsi
koyaanisqatsi

Reputation: 2813

I think the easiest way is to set it by Environment with start of Lua.
On an Unix like operating system i mean this...

€ date
Do 7. Apr 07:25:53 CEST 2022
€ env -i TZ=Europe/London lua -e "print(os.date())"
Thu Apr  7 06:26:47 2022
€ env -i TZ=Europe/Berlin lua -e "print(os.date())"
Thu Apr  7 07:26:58 2022

But feel free to write a time module.
Could look like...

€ env -i TZ=Europe/London lua -e "tzdate = setmetatable({}, {__index = {Berlin = function() return os.date(_, os.time() + 3600) end}}) print(tzdate.Berlin())"
Thu Apr  7 07:41:03 2022

And without env -i TZ= with @Egor Skriptunoff' hint a simple, hm, how could it be called, maybe Prototype?

$ /bin/lua -i
Lua 5.1.5  Copyright (C) 1994-2012 Lua.org, PUC-Rio
> tzdate = setmetatable({[0] = 7200}, {__tostring = function(self) return os.date('!%c', os.time() + self[#self]) end})
> print(tzdate)
Thu Apr  7 20:42:01 2022
> tzdate[1]=3600
> print(tzdate)
Thu Apr  7 19:42:43 2022
> tzdate[2]=7200
> print(tzdate)
Thu Apr  7 20:43:21 2022

This works while autoconverting tostring() is done by print().
To get the value in a variable or do other things that do no autoconverting use therefore tostring()...

> tzdate[3]=10800
> io.write(tzdate)
stdin:1: bad argument #1 to 'write' (string expected, got table)
stack traceback:
        [C]: in function 'write'
        stdin:1: in main chunk
        [C]: ?
> io.write(tostring(tzdate), '\n')
Thu Apr  7 21:59:40 2022

Upvotes: 2

Related Questions