Getting the Current Date with XQuery `current-date()`

Learn how to retrieve the current date in XQuery using the `current-date()` function. This tutorial explains its functionality, return value (XML dateTime), and provides examples demonstrating its use in generating timestamps and processing date-related information within XML documents.



Getting the Current Date with XQuery `current-date()`

Understanding `current-date()`

In XQuery, the `current-date()` function returns the current date as an XML dateTime value. This function is useful for various data processing tasks, particularly when working with XML documents that need to include timestamps. The returned date value reflects the server's time zone.

`current-date()` Syntax

The syntax is very simple:

current-date()

It takes no arguments.

Example: Retrieving the Current Date

This example shows how to retrieve the current date using the `current-date()` function in an XQuery file and then how to execute this using Java. The XQuery code is very simple: it assigns the current date to a variable and then outputs it. The Java code sets up a connection to an XQuery processor (using Saxon), executes the XQuery, and prints the result.

1. XQuery Code (`current-date.xqy`)

XQuery Code

let $date := current-date()
return $date

2. Java Code (`XQueryTester.java`)

Java Code

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import javax.xml.xquery.*;
import com.saxonica.xqj.SaxonXQDataSource;

public class XQueryTester {
    public static void main(String[] args) {
        try {
            execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    // ... execute method ...
}
Java `execute()` Method

private static void execute() throws Exception {
    InputStream inputStream = new FileInputStream(new File("current-date.xqy"));
    XQDataSource ds = new SaxonXQDataSource();
    XQConnection conn = ds.getConnection();
    XQPreparedExpression exp = conn.prepareExpression(inputStream);
    XQResultSequence result = exp.executeQuery();
    while (result.next()) {
        System.out.println(result.getItemAsString(null));
    }
}

Conclusion

The XQuery `current-date()` function is a simple yet powerful tool for retrieving the current date. It's a common function used in various XQuery applications involving time-related data processing and integration with other systems.