common/format

Formatting utilities for Rhino/RingoJS environments.

This module exposes a Java-style printf formatter and two timestamp helpers
that operate on epoch milliseconds and output in the local time zone.
Formatting patterns are backed by ringo/utils/dates (compatible with Java SimpleDateFormat).

Features

  • format(fmt, ...args): Delegates to java.lang.String.format with full specifier/flag support
  • formatTimestamp(ms): Local time as "yyyy-MM-dd HH:mm:ss.SSS"
  • formatTimestampForLog(ms): Local time as "yyyyMMdd_HHmmss" (sortable, log-friendly)
  • Safe integer boxing to satisfy %d expectations
  • Robust error handling (setError() on format failures; Error("Invalid timestamp") on bad input)

Usage Example

var { format, formatTimestamp, formatTimestampForLog } = require("sigma/common/format");

// Java-style formatting
var s1 = format("Fruits: %s, %s, %s", "Banana", "Orange", "Apple");
// → "Fruits: Banana, Orange, Apple"

// Positional arguments and flags
var s2 = format("Use flag $: %1$d, %2$s", 99, "abc");
// → "Use flag $: 99, abc"

// Human-readable timestamp (local time)
var ts = Date.parse("2025-06-15T08:30:45.067Z"); // ms
var pretty = formatTimestamp(ts);
// → "2025-06-15 08:30:45.067" (output depends on local time zone)

// Log-friendly timestamp (local time)
var key = formatTimestampForLog(Date.now());
// → "20250615_083045"

Notes

  • All timestamp APIs expect milliseconds. Convert seconds via ms = seconds * 1000.
  • Outputs are local time. For UTC, use UTC getters or normalize before formatting.
  • format() returns null on failure and records details via setError(e) / lastError().
  • Depends on ringo/utils/dates for Java-like date patterns.

(inner) format(format, …args) → {string|null}

--- Common Format Specifiers ---

Specifier Description Example Output
%s String "mingrisoft"
%c Character 'm'
%b Boolean true
%d Integer (decimal) 99
%x Integer (hexadecimal) FF
%o Integer (octal) 77
%f Float (decimal) 99.99
%a Float (hexadecimal) FF.35AE
%e Scientific notation 9.38e+5
%h Hash code A05A5198
%% Literal percent sign %
%n Line break (platform dependent)
%tx Date/time formatting (x = date/time flag) e.g., %tF → 2025-05-22

--- Flags With Format Specifiers ---

Flag Description Example Result
+ Include sign for positive/negative numbers ("%+d", 15) +15
- Left justify within specified width ("%-5d", 15) "15 "
0 Pad numeric value with leading zeros ("%04d", 99) "0099"
space Pad positive values with a space ("% 4d", 99) " 99"
, Use comma as thousands separator ("%,f", 9999.99) "9,999.990000"
( Wrap negative numbers in parentheses ("%(f", -99.99) "(99.990000)"
# Prefix for hex (0x), octal (0), or force decimal point ("%#x", 99) "0x63"
< Reuse previous argument ("%f and %<.2f", 99.45) "99.450000 and 99.45"
$ Argument index ("%2$s scored %1$d", 98,"Alice") "Alice scored 98"

For more details, see Java’s official documentation for

See:
Example
// Example 1: Basic string formatting
var { format } = require("sigma/common/format");
var str = format("Fruits: %s, %s, %s", "Banana", "Orange", "Apple");
print(str);
// Output:
// Fruits: Banana, Orange, Apple


// Example 2: Using parameter index ($) in formatting
var { format } = require("sigma/common/format");
var str1 = format("Use flag $: %1$d, %2$s", 99, "abc");
print(str1);
// Output:
// Use flag $: 99, abc

// If no format string is provided:
var result = format(); // Returns null and sets error: "Need at least one argument"
Parameters:
string format

Format string.

any args <repeatable>

Parameters referenced by the format specifier in the format string. The number of parameters is variable and can be 0.

Throws:

Sets an error via setError() if an exception occurs during formatting.

Returns:
string | null

If the execution is successful, The formatted string is returned; if the execution fails, null is returned. The error details can be obtained through lastError()

(inner) formatTimestamp(timestamp) → {string}

Formats a Unix timestamp (in milliseconds) into a human-readable string
using the local time zone.

Output pattern: YYYY-MM-DD HH:mm:ss.SSS

  • Year is 4 digits
  • Month/Day/Hour/Minute/Second are zero-padded to 2 digits
  • Milliseconds are zero-padded to 3 digits
Example
// Example 1: number input (ms)
var { formatTimestamp } = require("sigma/common/format");
// Assuming local time zone is UTC for demonstration:
// 2025-06-15T08:30:45.067Z  ->  1749985845067 (milliseconds)
var ts = Date.parse("2025-06-15T08:30:45.067Z"); // 1749985845067
formatTimestamp(ts);
// Sample output (if local time zone is UTC):
// "2025-06-15 08:30:45.067"
// NOTE: Actual output may differ if your local time zone is not UTC.

// Example 2: numeric string input (ms)
var { formatTimestamp } = require("sigma/common/format");
formatTimestamp("1749985845067");
// "2025-06-15 08:30:45.067"  (time-zone dependent)

// Example 3: invalid input
var { formatTimestamp } = require("sigma/common/format");
// Throws Error("Invalid timestamp")
formatTimestamp("not-a-number");
Parameters:
number | string timestamp

A Unix timestamp in milliseconds since 1970-01-01T00:00:00Z.
A numeric string is accepted and will be coerced via Number(...).

Throws:
Error

Throws Error("Invalid timestamp") if the input is null, undefined,
or cannot be converted to a valid number.

Returns:
string

A formatted date-time string in the local time zone.

(inner) formatTimestampForLog(timestamp) → {string}

Formats a Unix timestamp (in milliseconds) into a compact, log-friendly string
using the local time zone.

Output pattern: YYYYMMDD_HHmmss

  • Suitable for log lines, file names, or sortable keys.
  • Uses zero-padded values to maintain lexical sort order.
Example
// Example 1: basic usage (ms)
var { formatTimestampForLog } = require("sigma/common/format");
// Assuming local time zone is UTC for demonstration:
var ts = Date.parse("2025-06-15T08:30:45.067Z"); // 1749985845067
formatTimestampForLog(ts);
// Sample output (if local time zone is UTC):
// "20250615_083045"
// NOTE: Actual output may differ if your local time zone is not UTC.

// Example 2: from numeric string
var { formatTimestampForLog } = require("sigma/common/format");
formatTimestampForLog("1749985845067");
// "20250615_083045"  (time-zone dependent)

// Example 3: invalid input
var { formatTimestampForLog } = require("sigma/common/format");
// Throws Error("Invalid timestamp")
formatTimestampForLog(undefined);
Parameters:
number | string timestamp

A Unix timestamp in milliseconds since 1970-01-01T00:00:00Z.
A numeric string is accepted and will be coerced via Number(...).

Throws:
Error

Throws Error("Invalid timestamp") if the input is null, undefined,
or cannot be converted to a valid number.

Returns:
string

A compact date-time string in the local time zone, e.g. 20250615_083045.