Razen Examples

Learn Razen through practical examples and code snippets.

Date Library (date)

# Date Library (date) # Difficulty: 1 # Description: Examples of using the Date Library in Razen ## Introduction The Date Library (`date`) provides functions for working with dates and timestamps in Razen. This library helps you get the current date, format dates, parse date strings, and perform date calculations. ## Library Overview ### Date Library Functions - `now` → Gets the current timestamp in seconds since the Unix epoch - `year` → Gets the current year - `month` → Gets the current month (1-12) - `day` → Gets the current day of month - `format` → Formats a timestamp as a string - `parse` → Parses a date string with a format - `add_days` → Adds days to a timestamp - `add_months` → Adds months to a timestamp - `add_years` → Adds years to a timestamp - `weekday` → Gets the day of week (0 = Sunday, 6 = Saturday) - `weekday_name` → Gets the name of the weekday - `days_in_month` → Gets the number of days in a month - `is_leap_year` → Checks if a year is a leap year - `diff_days` → Gets the difference in days between two dates ## How to Use the Date Library ### Library Import To use the Date Library in Razen, you first need to import it using the `lib` keyword: ```razen lib date; ``` ### Function Calling Once imported, you can call functions from the library using the double colon `::` syntax: ```razen date::functionName(parameters); ``` **Note about bracket notation (Legacy):** In older versions of Razen (before beta v0.1.75), you could also use bracket notation for library functions: ```razen # DEPRECATED - Only works in Razen before beta v0.1.75 date[functionName](parameters); ``` This syntax is no longer supported in newer versions of Razen. ## Basic Examples ### Getting Current Date Information ```razen # Import the date library lib date; # Get current timestamp (Unix timestamp in seconds) num now = date::now(); show "Current timestamp: " + now; # Output: Current timestamp: 1717517400 (depends on your timezone) # Get current year num year = date::year(); show "Current year: " + year; # Output: Current year: 2025 (depends on current year) # Get current month (1-12) num month = date::month(); show "Current month: " + month; # Output: Current month: 6 (depends on current month) # Get current day of month num day = date::day(); show "Current day: " + day; # Output: Current day: 3 (depends on current day) ``` ### Formatting Dates ```razen # Import the date library lib date; # Get current timestamp num now = date::now(); # Gives a number representing the current timestamp in milliseconds since the Unix epoch. # Format date as a string str formatted = date::format(now, "YYYY-MM-DD"); # Format the date as a string show "Formatted date: " + formatted; # Output: Formatted date: 2025-06-03 # Different format examples show "Full date and time: " + date::format(now, "YYYY-MM-DD HH:mm:ss"); # Output: 2025-06-03 21:45:30 show "Short date: " + date::format(now, "MM/DD/YYYY"); # Output: 06/03/2025 show "Long date: " + date::format(now, "MM DD, YYYY"); # Output: 06 03, 2025 ``` ### Parsing Date Strings ```razen # Import the date library lib date; # Parse a date string into a timestamp str dateString = "2025-06-03"; num parsedTimestamp = date::parse(dateString, "YYYY-MM-DD"); show "Parsed timestamp: " + parsedTimestamp; # Format the parsed timestamp to verify str formatted = date::format(parsedTimestamp, "MM, DD, YYYY"); show "Formatted parsed date: " + formatted; # Output: 06, 03, 2025 # Parse different date formats str dateString2 = "06/03/2025"; num parsedTimestamp2 = date::parse(dateString2, "MM/DD/YYYY"); show "Parsed timestamp 2: " + parsedTimestamp2; str dateString3 = "06, 03, 2025"; num parsedTimestamp3 = date::parse(dateString3, "MM, DD, YYYY"); show "Parsed timestamp 3: " + parsedTimestamp3; ``` ### Date Manipulation ```razen # Import the date library lib date; # Get current timestamp num now = date::now(); str currentDate = date::format(now, "YYYY-MM-DD"); show "Current date: " + currentDate; # Output: Current date: 2025-06-03 # Add days to current date num futureDate = date::add_days(now, 7); str futureDateFormatted = date::format(futureDate, "YYYY-MM-DD"); show "Date after adding 7 days: " + futureDateFormatted; # Output: 2025-06-10 # Add months to current date num futureMonth = date::add_months(now, 3); str futureMonthFormatted = date::format(futureMonth, "YYYY-MM-DD"); show "Date after adding 3 months: " + futureMonthFormatted; # Output: 2025-09-03 # Add years to current date num futureYear = date::add_years(now, 1); str futureYearFormatted = date::format(futureYear, "YYYY-MM-DD"); show "Date after adding 1 year: " + futureYearFormatted; # Output: 2026-06-03 ``` ### Weekday Information ```razen # Import the date library lib date; # Get current timestamp num now = date::now(); # Get weekday (0 = Sunday, 6 = Saturday) num weekday = date::weekday(now); show "Current weekday (0-6): " + weekday; # Output: Current weekday (0-6): 2 (Tuesday) # Get weekday name str weekdayName = date::weekday_name(now); show "Current weekday name: " + weekdayName; # Output: Current weekday name: Tuesday # Format date with weekday for verification str formattedWithWeekday = date::format(now, "C_D, C_M, DD, YYYY"); show "Formatted with weekday: " + formattedWithWeekday; # Output: Tuesday, June, 03, 2025 ``` ### Month Information and Leap Years ```razen # Import the date library lib date; # Get days in current month num year = date::year(); num month = date::month(); num daysInMonth = date::days_in_month(year, month); show "Days in current month (" + month + "/" + year + "): " + daysInMonth; # Output: Days in current month (6/2025): 30 # Check days in February for leap year and non-leap year show "Days in February 2024 (leap year): " + date::days_in_month(2024, 2); # Output: 29 show "Days in February 2025 (non-leap year): " + date::days_in_month(2025, 2); # Output: 28 # Check if years are leap years show "Is 2024 a leap year? " + date::is_leap_year(2024); # Output: true show "Is 2025 a leap year? " + date::is_leap_year(2025); # Output: false show "Is 2000 a leap year? " + date::is_leap_year(2000); # Output: true show "Is 1900 a leap year? " + date::is_leap_year(1900); # Output: false ``` ### Date Difference ```razen # Import the date library lib date; # Get current timestamp num now = date::now(); # Calculate difference between dates num futureDate = date::add_days(now, 7); num daysDiff = date::diff_days(now, futureDate); show "Difference in days: " + daysDiff; # Output: Difference in days: 7 # Calculate age in days str birthdate = "1990-01-15"; num birthdateTimestamp = date::parse(birthdate, "YYYY-MM-DD"); num ageInDays = date::diff_days(birthdateTimestamp, now); show "Age in days for someone born on " + birthdate + ": " + ageInDays; ``` ## Advanced Examples ### Date Validation Function ```razen # Import the date library lib date; # Function to validate if a date string is valid fun isValidDate(dateStr, format) { try { # Try to parse the date string num timestamp = date::parse(dateStr, format); # If parsing succeeds and results in a valid timestamp if (timestamp > 0) { # Format the timestamp back to a date string for verification str formatted = date::format(timestamp, format); # Check if the formatted date matches the original date string return formatted == dateStr; } return false; } catch (err) { # If parsing fails, the date is invalid return false; } } # Test the validation function show "Is '2025-06-03' valid? " + isValidDate("2025-06-03", "YYYY-MM-DD"); # Output: true show "Is '2025-02-30' valid? " + isValidDate("2025-02-30", "YYYY-MM-DD"); # Output: false (February doesn't have 30 days) show "Is '2025-13-01' valid? " + isValidDate("2025-13-01", "YYYY-MM-DD"); # Output: false (Invalid month) ``` ### Date Range Generator ```razen # Import the date library lib date; # Function to generate an array of dates within a range fun generateDateRange(startDate, endDate, format) { # Parse start and end dates num startTimestamp = date::parse(startDate, format); num endTimestamp = date::parse(endDate, format); # Check if dates are valid if (startTimestamp <= 0 || endTimestamp <= 0) { return "Invalid date format"; } # Check if end date is after start date if (startTimestamp > endTimestamp) { return "End date must be after start date"; } # Calculate number of days between dates num daysDiff = date::diff_days(startTimestamp, endTimestamp); # Generate array of dates str dates = []; for (num i = 0; i <= daysDiff; i = i + 1) { num currentTimestamp = date::add_days(startTimestamp, i); str currentDate = date::format(currentTimestamp, format); dates.push(currentDate); } return dates; } # Generate a range of dates str dateRange = generateDateRange("2025-06-01", "2025-06-07", "YYYY-MM-DD"); show "Date range: " + dateRange; # Output: Date range: ["2025-06-01", "2025-06-02", "2025-06-03", "2025-06-04", "2025-06-05", "2025-06-06", "2025-06-07"] ``` ### Age Calculator ```razen # Import the date library lib date; # Function to calculate age in years, months, and days fun calculateAge(birthdate, format) { # Parse birthdate num birthdateTimestamp = date::parse(birthdate, format); # Get current timestamp num now = date::now(); # Extract birth year, month, and day num birthYear = date::year(birthdateTimestamp); num birthMonth = date::month(birthdateTimestamp); num birthDay = date::day(birthdateTimestamp); # Extract current year, month, and day num currentYear = date::year(now); num currentMonth = date::month(now); num currentDay = date::day(now); # Calculate age in years num years = currentYear - birthYear; # Adjust years if birthday hasn't occurred this year yet if (currentMonth < birthMonth || (currentMonth == birthMonth && currentDay < birthDay)) { years = years - 1; } # Calculate months num months = currentMonth - birthMonth; if (months < 0) { months = months + 12; } # Adjust months if day of month hasn't occurred yet if (currentDay < birthDay) { months = months - 1; if (months < 0) { months = months + 12; } } # Calculate days num days = currentDay - birthDay; if (days < 0) { # Get days in previous month num prevMonth = currentMonth - 1; if (prevMonth == 0) { prevMonth = 12; years = years - 1; } days = days + date::days_in_month(currentYear, prevMonth); } # Create result object map result = { "years": years, "months": months, "days": days, "totalDays": date::diff_days(birthdateTimestamp, now) }; return result; } # Calculate age for a birthdate str birthdate = "1990-05-15"; map age = calculateAge(birthdate, "YYYY-MM-DD"); show "Age for someone born on " + birthdate + ":"; show "Years: " + age["years"]; show "Months: " + age["months"]; show "Days: " + age["days"]; show "Total days: " + age["totalDays"]; ``` ## Practical Application: Event Scheduler ```razen # Import the date library lib date; # Simple event scheduler application class EventScheduler { # Constructor init() { this.events = []; } # Add a new event fun addEvent(str title, str eventDate, str description) { # Parse event date num eventTimestamp = date::parse(eventDate, "YYYY-MM-DD"); # Validate date if (eventTimestamp <= 0) { return "Invalid date format. Please use YYYY-MM-DD."; } # Create event object map event = { "id": this.events.length + 1, "title": title, "date": eventDate, "timestamp": eventTimestamp, "description": description, "weekday": date::weekday_name(eventTimestamp) }; # Add to events array this.events.push(event); return "Event '" + title + "' scheduled for " + eventDate + " (" + event["weekday"] + ")"; } # Get all events fun getAllEvents() { return this.events; } # Get events for a specific date fun getEventsByDate(str eventDate) { str filteredEvents = []; for (num i = 0; i < this.events.length; i = i + 1) { if (this.events[i]["date"] == eventDate) { filteredEvents.push(this.events[i]); } } return filteredEvents; } # Get upcoming events fun getUpcomingEvents(num days) { # Get current timestamp num now = date::now(); # Calculate end date num endTimestamp = date::add_days(now, days); # Filter upcoming events str upcomingEvents = []; for (num i = 0; i < this.events.length; i = i + 1) { num eventTimestamp = this.events[i]["timestamp"]; if (eventTimestamp >= now && eventTimestamp <= endTimestamp) { # Add days until event num daysUntil = date::diff_days(now, eventTimestamp); map event = this.events[i]; event["daysUntil"] = daysUntil; upcomingEvents.push(event); } } return upcomingEvents; } # Display events in a formatted way fun displayEvents(str events) { if (events.length == 0) { return "No events found."; } str result = "=== Events ===\n"; for (num i = 0; i < events.length; i = i + 1) { map event = events[i]; result = result + "ID: " + event["id"] + "\n"; result = result + "Title: " + event["title"] + "\n"; result = result + "Date: " + event["date"] + " (" + event["weekday"] + ")\n"; if (event["daysUntil"] != null) { result = result + "Days until event: " + event["daysUntil"] + "\n"; } result = result + "Description: " + event["description"] + "\n\n"; } return result; } } # Create a new scheduler EventScheduler scheduler = new EventScheduler(); # Add events show scheduler.addEvent("Team Meeting", "2025-06-10", "Weekly team sync-up"); show scheduler.addEvent("Project Deadline", "2025-06-15", "Final project submission"); show scheduler.addEvent("Conference", "2025-07-05", "Annual industry conference"); show scheduler.addEvent("Birthday Party", "2025-06-20", "John's birthday celebration"); # Display all events show scheduler.displayEvents(scheduler.getAllEvents()); # Display events for a specific date show "Events on 2025-06-15:"; show scheduler.displayEvents(scheduler.getEventsByDate("2025-06-15")); # Display upcoming events in the next 14 days show "Upcoming events in the next 14 days:"; show scheduler.displayEvents(scheduler.getUpcomingEvents(14)); ``` ## Summary The Date Library in Razen provides essential functions for working with dates: - Getting current date information (`now`, `year`, `month`, `day`) - Formatting and parsing dates (`format`, `parse`) - Date manipulation (`add_days`, `add_months`, `add_years`) - Weekday information (`weekday`, `weekday_name`) - Month and leap year utilities (`days_in_month`, `is_leap_year`) - Date difference calculation (`diff_days`) These functions help you work with dates efficiently in your Razen programs.