Time API
Overview
Internally Moodle always stores all times in unixtime format (number of seconds since epoch) which is independent of timezones.
The Time API is used to display proper date-time depending on user or site timezones.
Functions
Functions related to time api can be found in lib/moodlelib.php.
- Time API's for current user
- make_timestamp - Given date-time, it produces a GMT timestamp for current user.
- userdate - Gets formatted string that represents a date in user time
- usertime - Given a GMT timestamp (seconds since epoch), offsets it by the timezone. eg 3pm in India is 3pm GMT - 5.5 * 3600 seconds
- usergetdate - Given a timestamp in GMT, returns an array that represents the date-time in user time
- usergetmidnight - Given a date, return the GMT timestamp of the most recent midnight for the current user.
- usertimezone - Returns current user's timezone
- get_user_timezone_offset - Returns user's timezone difference from GMT in hours
- System Time API
- format_time - Format a date/time (seconds) as weeks, days, hours etc as needed
- get_timezone_offset - Systems's timezone difference from GMT in seconds
- dst_changes_for_year - Calculates the required DST change and returns a Timestamp Array
- dst_offset_on - Calculates the Daylight Saving Offset for a given date/time (timestamp)
- find_day_in_month - Calculates when the day appears in specific month
- days_in_month - Calculate number of days in a given month
- dayofweek - Calculate the position in the week of a specific calendar day
Glossary
Timezone
Moodle supports following timezone formats:
- UTC (specifically UTC−11 to UTC+11)
- Time offsets from UTC (int +-(0-13) or float +-(0.5-12.5))
- World timezones (Australia/Perth)
Location
Timezone depends on en:Location of the user and can be forced upon by administrator.
DST
DST is abbreviation of Day light saving. Many countries, and sometimes just certain regions of countries, adopt daylight saving time (also known as "Summer Time") during part of the year. Moodle automatically calculates DST for current user, depending on user location.
Examples
Time API's for current user
Prints a formatted date in user time
// Get current day, month and year for current user. $date = usergetdate(time()); list($d, $m, $y) = array($date['mday'], $date['mon'], $date['year']); // Print formatted date in user time. echo userdate(make_timestamp($y, $m), "Current user time");
System Time API
Find start month day
$now = usergetdate(time()); echo find_day_in_month($now['mday'] - 6, $startweekday, $now['mon'], $now['year']);