Logo

Programming-Idioms

  • Rust
  • Pascal
  • Obj-c

Idiom #99 Format date YYYY-MM-DD

Assign to the string x the value of the fields (year, month, day) of the date d, in format YYYY-MM-DD.

@import Foundation;
// once
static NSDateFormatter *df; 
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
  df=[[NSDateFormatter alloc] init];
  df.locale=[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
  df.timeZone=[NSTimeZone timeZoneForSecondsFromGMT:0];
  df.dateFormat=@"yyyy-MM-dd";
});
// then, wherever needed
NSString *x=[df stringFromDate:d];

Most time, it's much better to use user-defined system-wide date formats (through dateStyle and timeStyle) instead of fixed ones.
use time::macros::format_description;
let format = format_description!("[year]-[month]-[day]");
let x = d.format(&format).expect("Failed to format the date");

time crate is better maintained.
extern crate chrono;
use chrono::prelude::*;
Utc::today().format("%Y-%m-%d")
Uses sysutils;
DefaultFormatSettings.ShortDateFormat := 'yyyy-mm-dd';
X := DateToStr(D);

D is a TDateTime.
with Ada.Calendar.Formatting;
X : constant String :=
    Ada.Calendar.Formatting.Image (D) (1 .. 10);

The Image function returns time as well therefore the slice.

New implementation...