Programming-Idioms

This language bar is your friend. Select your favorite languages!

Idiom #99 Format date YYYY-MM-DD

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

D = erlang:localtime(),
{{Year, Month, Day}, {_Hour, _Minute, _Second}} = D,
X = lists:flatten(io_lib:format("~4..0w-~2..0w-~2..0w", [Year, Month, Day])).  % "2017-07-02"
IDENTIFICATION DIVISION.
PROGRAM-ID. date format.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 curr-date.
   03 yyyy      pic 9(4).
   03 mm        pic 9(2).
   03 dd        pic 9(2).
01 d.
   03 year      pic 9(4). 
   03 FILLER    pic x VALUE '-'.
   03 month     pic 99. 
   03 FILLER    pic x VALUE '-'.
   03 day       pic 99. 
PROCEDURE DIVISION.
   MOVE FUNCTION CURRENT-DATE TO curr-date
   MOVE yyyy to year
   MOVE mm   to month
   MOVE dd   to day
   DISPLAY d 
STOP RUN.
#include <string>
#include <ctime>
#include <iostream>
#include <iomanip>
int main()
{
	char x[32]{};
	time_t a = time(nullptr);
	struct tm d;
	if (localtime_s(&d, &a) == 0) {
		strftime(x, sizeof(x), "%F", &d);
		std::cout << x << std::endl;
	}

	return 0;

}
string x = d.ToString("yyyy-MM-dd");
import std.datetime;
string x = Date(1993, 10, 26).toISOExtString;
import 'package:intl/intl.dart';
x = DateFormat('YYYY-MM-DD').format(d);
x = Date.to_iso8601(d)
program p
integer, dimension(8) :: d
character(len=10) :: x
call date_and_time (values=d)
write(x,'(i4.4,"-",i2.2,"-",i2.2)')d(1),d(2),d(3)
print *,'DATE=',x
end program p
import "time"
x := d.Format("2006-01-02")
import Data.Time.Calendar
x = showGregorian d
const today = new Date();
const isoDate = today.toISOString().slice(0, 10);
let x = d.toISOString().slice(0, 10 /* 'yyyy-mm-dd'.length */)
String x = String.format("%1$tY-%1$tm-%1$td", d)
import java.text.SimpleDateFormat;
String x = new SimpleDateFormat("yyyy-MM-dd").format(d);
x = os.date("%F",d)
$formattedVar = date("Y-m-d", strtotime($unformattedVar));

# Take the unformated Variable, let PHP do it's best to
# 'understand' it and then format the resultant into the 
# desired format.
$x = date("Y-m-d", strtotime($d));
Uses sysutils;
DefaultFormatSettings.ShortDateFormat := 'yyyy-mm-dd';
X := DateToStr(D);
use POSIX 'strftime';
$x = strftime "%Y-%m-%d", localtime($d);
from datetime import date
d = date.today()
x = d.isoformat()
from datetime import date
d = date(2016, 9, 28)
x = d.strftime('%Y-%m-%d')
require 'date'
d = Date.today
x = d.to_s
extern crate chrono;
use chrono::prelude::*;
Utc::today().format("%Y-%m-%d")
Dim d As Date = Today
Dim x As String = d.ToString("yyyy-MM-dd")

Do you know the best way to do this in your language ?
New implementation...

Idiom created by

programming-idioms.org

Related idioms