Learn R Programming

ksformat (version 0.3.5)

fnew_date: Create Date/Time Format

Description

Creates a format object for date, time, or datetime values using SAS format names or custom R strftime patterns. The format is automatically registered in the global format library.

Usage

fnew_date(pattern, name = NULL, type = "auto", .missing = NULL)

Value

A ks_format object with date/time type, registered in the library.

Arguments

pattern

Character. Either a SAS format name (e.g., "DATE9.", "MMDDYY10.", "TIME8.", "DATETIME20.") or a custom R strftime pattern (e.g., "%Y-%m-%d").

name

Character. Name to register the format under. Defaults to the SAS format name (with period) or the pattern itself.

type

Character. Type of format: "date", "time", "datetime", or "auto" (auto-detect from SAS name). Must be specified for custom strftime patterns.

.missing

Character. Label for missing values (NA). Default NULL.

Details

SAS format names are resolved automatically:

  • Date: DATE9., DDMMYY10., MMDDYY10., YYMMDD10., MONYY7., YEAR4., WEEKDATE., WORDDATE., etc.

  • Time: TIME8., TIME5., HHMM., HOUR., MMSS.

  • Datetime: DATETIME20., DATETIME13., etc.

Numeric input is converted using R epoch ("1970-01-01"):

  • Dates: numeric values are interpreted as days since 1970-01-01

  • Datetimes: numeric values are interpreted as seconds since 1970-01-01

  • Times: always treated as seconds since midnight

Examples

Run this code
# Use a SAS format name
fnew_date("DATE9.", name = "mydate")
fput(as.Date("2020-01-01"), "mydate")
# [1] "01JAN2020"

# Use directly without pre-creating
fputn(as.Date("2020-06-15"), "MMDDYY10.")
# [1] "06/15/2020"

# Custom strftime pattern (e.g., Russian style: DD.MM.YYYY)
fnew_date("%d.%m.%Y", name = "ru_date", type = "date")
fput(as.Date(c("1990-03-25", "1985-11-03", "2000-07-14")), "ru_date")

# Custom format with missing value label
fnew_date("MMDDYY10.", name = "us_date", .missing = "NO DATE")
fput(c(as.Date("2025-01-01"), NA, as.Date("2025-12-31")), "us_date")
# [1] "01/01/2025" "NO DATE" "12/31/2025"

# Numeric dates (days since 1970-01-01, R epoch)
r_days <- as.numeric(as.Date("2025-01-01"))
fputn(r_days, "DATE9.")

# Multiple SAS date formats applied directly
today <- Sys.Date()
fputn(today, "DATE9.")
fputn(today, "MMDDYY10.")
fputn(today, "YYMMDD10.")
fputn(today, "MONYY7.")
fputn(today, "WORDDATE.")
fputn(today, "QTR.")

# Time formatting (seconds since midnight)
fputn(c(0, 3600, 45000, 86399), "TIME8.")
fputn(c(0, 3600, 45000), "HHMM.")

# Datetime formatting
now <- Sys.time()
fputn(now, "DATETIME20.")
fputn(now, "DTDATE.")
fputn(now, "DTYYMMDD.")
fclear()

Run the code above in your browser using DataLab