← Back to lessons

40 Time

Hard

The time package provides time-related types, including date and time, time interval, monotonic time, and time zone, and provides functionality of calculation and comparison.

Parsing time from a string has some requirements, it must contain the current year and date. If information about the hour, minute and second is not included they all default to 0, the same is true for timezonde which defaults to Local. You can get a complete table of the letter formatting in cangjie through the docs (API Reference/std Module/std.time Package/time Package).

In the examples shown, we first create a DateTime object, then use the toString with the given pattern, only to parse that string back into a DateTime object.

DateTime comparisons are also possible accross timezones, as you can see here, the datetime variable is on the Shanghai timezone, and yet it is still equal to the new_york timezone, since the offset between them is 12 hours.

Monotime can also be used to count time, and evaluate program speed as shown.

Time.cj
import std.time.*

main() {
    let pattern = "yyyy/MM/dd HH:mm:ssSSS OO"
    let datetime = DateTime.of(
        year: 2024,
        month: May,
        dayOfMonth: 22,
        hour: 8,
        minute: 34,
        second: 56,
        nanosecond: 789000000,
        timeZone: TimeZone.load("Asia/Shanghai")
    )
    let str = datetime.toString(pattern)
    println(str)
    println(DateTime.parse(str, pattern))

    let new_york1 = DateTime.of(year: 2024, month: May, dayOfMonth: 21,
        hour: 20, minute: 34, second: 56, nanosecond: 789000000,
        timeZone: TimeZone.load("America/New_york"))

    println(datetime == new_york1)

    let yr = datetime.year
    let dayOfYear = datetime.dayOfYear
    let (isoYear, isoWeek) = datetime.isoWeek

    println("${dayOfYear}th day, ${isoWeek}th week of ${isoYear}")

    let start = MonoTime.now()
    for (_ in 0..200) {
        DateTime.now()
    }
    let end = MonoTime.now()
    let result = end - start
    println("total cost: ${result.toNanoseconds()}ns")
}