qubodup
qubodup

Reputation: 9623

Lua - get time and date of specific time zone

I want the time and date of a specific timezone in Lua, formatted in way, os.date("%a %b %d, %H:%M") would return it.

I know that os.date("!%a %b %d, %H:%M") (added exclamation mark "!") gives me UTC time but how do I move from there and offset the requested time?

In my case the desired timezone is UTC+08:00.

Upvotes: 6

Views: 13036

Answers (1)

qubodup
qubodup

Reputation: 9623

os.date accepts two parameters:

os.date ( [format [, time]] )

The time parameter - in seconds - can be used to offset the returned value.

Since os.time() returns the current time in seconds, you can simply add your offset (8), multiplied by seconds in a minute (60), multiplied by minutes in a second (60).

os.date( "!%a %b %d, %H:%M", os.time() + 8 * 60 * 60 )

If you're in UTC+01:00, these are the kinds of output you would receive:

> os.date( "%a %b %d, %H:%M")
Wed Mar 16, 09:33
> os.date( "!%a %b %d, %H:%M")
Wed Mar 16, 08:33
> os.date( "!%a %b %d, %H:%M", os.time() + 8 * 60 * 60 )
Wed Mar 16, 16:33

If your offset is not by full hours, you have to use a decimal number of course. For example: UTC+07:30 would be 7.5 in the equation.

Upvotes: 10

Related Questions