Date format: Difference between revisions

From Rosetta Code
Content added Content deleted
Line 1,000: Line 1,000:
puts [clock format $now -format "%Y-%m-%d"]
puts [clock format $now -format "%Y-%m-%d"]
puts [clock format $now -format "%A, %B %d, %Y"]</lang>
puts [clock format $now -format "%A, %B %d, %Y"]</lang>
=={{header|TUSCRIPT}}==
<lang tuscript>
$$ MODE TUSCRIPT
SET dayofweek = DATE (today,day,month,year,number)

SET months=*
DATA January
DATA Februari
DATA March
DATA April
DATA Mai
DATA June
DATA July
DATA August
DATA September
DATA October
DATA November
DATA December

SET days="Monday'Tuesday'Wendsday'Thursday'Fryday'Saturday'Sonday"

SET nameofday =SELECT (days,^#dayofweek)
SET nameofmonth=SELECT (months,^#month)

SET format1=JOIN (year,"-",month,day)
SET format2=CONCAT (nameofday,", ",nameofmonth," ",day, ", ",year)

PRINT format1
PRINT format2
</lang>


=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==

Revision as of 16:02, 4 January 2011

Task
Date format
You are encouraged to solve this task according to the task description, using any language you may know.
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task.

Display the current date in the formats of "2007-11-10" and "Sunday, November 10, 2007".

ABAP

<lang ABAP> report zdate. data: lv_month type string,

     lv_weekday type string,
     lv_date type string,
     lv_day type c.

call function 'DATE_COMPUTE_DAY'

 exporting date = sy-datum
 importing day  = lv_day.

select single ltx from t247 into lv_month

 where spras = sy-langu and
 mnr = sy-datum+4(2).

select single langt from t246 into lv_weekday

 where sprsl = sy-langu and
 wotnr = lv_day.

concatenate lv_weekday ', ' lv_month ' ' sy-datum+6(2) ', ' sy-datum(4) into lv_date respecting blanks. write lv_date. concatenate sy-datum(4) '-' sy-datum+4(2) '-' sy-datum+6(2) into lv_date. write / lv_date. </lang>

Ada

<lang ada>with Ada.Calendar; use Ada.Calendar; with Ada.Calendar.Formatting; use Ada.Calendar.Formatting; with Ada.Text_IO; use Ada.Text_IO;

procedure Date_Format is

  function Image (Month : Month_Number) return String is
  begin
     case Month is
        when 1  => return "January";
        when 2  => return "February";
        when 3  => return "March";
        when 4  => return "April";
        when 5  => return "May";
        when 6  => return "June";
        when 7  => return "July";
        when 8  => return "August";
        when 9  => return "September";
        when 10 => return "October";
        when 11 => return "November";
        when 12 => return "December";
     end case;
  end Image;
  function Image (Day : Day_Name) return String is
  begin
     case Day is
        when Monday    => return "Monday";
        when Tuesday   => return "Tuesday";
        when Wednesday => return "Wednesday";
        when Thursday  => return "Thursday";
        when Friday    => return "Friday";
        when Saturday  => return "Saturday";
        when Sunday    => return "Sunday";
     end case;
  end Image;
  Today : Time := Clock;

begin

  Put_Line (Image (Today) (1..10));
  Put_Line
  (  Image (Day_Of_Week (Today)) & ", "
  &  Image (Ada.Calendar.Month (Today))
  &  Day_Number'Image (Ada.Calendar.Day (Today)) & ","
  &  Year_Number'Image (Ada.Calendar.Year (Today))
  );

end Date_Format;</lang> Sample output:

2008-10-03
Friday, October 3, 2008

ALGOL 68

Works with: ALGOL 68 version Standard - using the a68g standard library
Works with: ALGOL 68G version Any - tested with release mk15-0.8b.fc9.i386

Note: the format can be used for both printing and reading date data.

<lang algol68># define the layout of the date/time as provided by the call to local time # STRUCT ( INT sec, min, hour, mday, mon, year, wday, yday, isdst) tm = (6,5,4,3,2,1,7,~,8);

FORMAT # some useful format declarations #

 ymd repr = $4d,"-"2d,"-"2d$,
 month repr =    $c("January","February","March","April","May","June","July",
                    "August","September","October","November","December")$,
 week day repr = $c("Sunday","Monday","Tuesday","Wednesday",
                    "Thursday","Friday","Saturday")$,
 dmdy repr =     $f(week day repr)", "f(month repr)" "g(-0)", "g(-4)$,
 mon  = $c("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")$,
 wday = $c("Sun","Mon","Tue","Wed","Thu","Fri","Sat")$,
 tz   = $c("MSK","MSD")$,
 unix time repr = $f(wday)" "f(mon)z-d," "dd,":"dd,":"dd," "f(tz)" "dddd$;

[]INT now = local time;

printf((ymd repr, now[year OF tm:mday OF tm], $l$)); printf((dmdy repr, now[wday OF tm], now[mon OF tm], now[mday OF tm], now[year OF tm], $l$));

printf((unix time repr, now[wday OF tm], now[mon OF tm], now[mday OF tm],

                       now[hour OF tm:sec OF tm], now[isdst OF tm]+1, now[year OF tm], $l$))</lang>

Sample output:

2009-04-08
Wednesday, April 8, 2009
Wed Apr  8 18:04:02 MSD 2009

AutoHotkey

<lang autohotkey>FormatTime, Date1, 20071110235959, yyyy-MM-dd ; "2007-11-10" FormatTime, Date2, 20071110235959, LongDate  ; "Sunday, November 10, 2007" MsgBox %Date1% `n %Date2%</lang>

AWK

Works with: Gawk

<lang awk>$ awk 'BEGIN{t=systime();print strftime("%Y-%m-%d",t)"\n"strftime("%A, %B %d, %Y",t)}' 2009-05-15 Friday, May 15, 2009</lang>

BASIC

Works with: FreeBASIC

<lang freebasic>#include "vbcompat.bi"

DIM today As Double = Now()

PRINT Format(today, "yyyy-mm-dd") PRINT Format(today, "dddd, mmmm d, yyyy")</lang>

C

<lang c>#include <stdio.h>

  1. include <time.h>
  1. define MAX_BUF 50

int main() {

  time_t seconds;
  struct tm *now;
  char buf[MAX_BUF];
  seconds = time(NULL);
  now = localtime(&seconds);
  printf("%d-%d-%d\n", now->tm_year + 1900, now->tm_mon + 1, now->tm_mday);
  const char *months[] = {"January", "February", "March", "April", "May", "June",
                          "July", "August", "September", "October", "November", "December"};
  const char *days[] = {"Sunday", "Monday", "Tuesday", "Wednesday",
                        "Thursday","Friday","Saturday"};
  printf("%s, %s %d, %d\n",days[now->tm_wday],
                           months[now->tm_mon],
                           now->tm_mday, now->tm_year + 1900);
  /* using the strftime (the result depends on the locale) */
  strftime(buf, MAX_BUF, "%A, %B %e, %Y", now);
  printf("%s\n", buf);

   return 0;

}</lang> Sample output:

2009-5-13
Wednesday, May 13, 2009
Wednesday, May 13, 2009

C++

<lang cpp>// Display the current date in the formats of "2007-11-10" // and "Sunday, November 10, 2007".

  1. include <vector>
  2. include <string>
  3. include <iostream>
  4. include <ctime>

/** Return the current date in a string, formatted as either ISO-8601

*  or "Weekday-name, Month-name Day, Year".
*
*  The date is initialized when the object is created and will return
*  the same date for the lifetime of the object.  The date returned
*  is the date in the local timezone.
*/

class Date {

   const size_t size;
   std::vector<char> out;
   struct tm ltime;

public:

   /// Default constructor.
   Date() : size(200), out(size), ltime()
   {
       time_t t = time(0);
       localtime_r(&t, &ltime);
   }
   
   /** Return the date based on a format string.  The format string is
    *  fed directly into strftime().  See the strftime() documentation
    *  for information on the proper construction of format strings.
    *
    *  @param[in] fmt is a valid strftime() format string.
    *
    *  @return a string containing the formatted date, or a blank string
    *      if the format string was invalid or resulted in a string that
    *      exceeded the internal buffer length.
    */
   std::string getDate(const char* fmt)
   {
       const size_t result = strftime(&(out[0]), size, fmt, &ltime);
       return std::string(out.begin(), out.begin() + result);
   }
   
   /** Return the date in ISO-8601 date format.
    *
    *  @return a string containing the date in ISO-8601 date format.
    */
   std::string getISODate() {return getDate("%F");}
   
   /** Return the date formatted as "Weekday-name, Month-name Day, Year".
    *
    *  @return a string containing the date in the specified format.
    */
   std::string getTextDate() {return getDate("%A, %B %d, %Y");}

};

int main() {

   Date d;
   std::cout << d.getISODate() << std::endl;
   std::cout << d.getTextDate() << std::endl;
   return 0;

}</lang> Sample output:

2009-05-14
Thursday, May 14, 2009

C#

<lang csharp>using System;

namespace RosettaCode.DateFormat {

   class Program
   {
       static void Main(string[] args)
       {
           DateTime today = DateTime.Now.Date;
           Console.WriteLine(today.ToString("yyyy-MM-dd"));
           Console.WriteLine(today.ToString("dddd, MMMMM d, yyyy"));
       }
   }

}</lang>

Clojure

<lang lisp>(let [now (.getTime (java.util.Calendar/getInstance))

     f1  (java.text.SimpleDateFormat. "yyyy-MM-dd")
     f2  (java.text.SimpleDateFormat. "EEEE, MMMM dd, yyyy")]
 (println (.format f1 now))
 (println (.format f2 now)))</lang>

Sample output:

2009-12-06
Sunday, December 06, 2009

ColdFusion

<lang coldfusion><cfoutput>

   #dateFormat(Now(), "YYYY-MM-DD")#
#dateFormat(Now(), "DDDD, MMMM DD, YYYY")#

</cfoutput></lang>

Common Lisp

<lang lisp>(defconstant *day-names*

   #("Monday" "Tuesday" "Wednesday" "Thursday" "Friday" "Saturday" "Sunday"))

(defconstant *month-names*

   #(nil "January" "February" "March" "April" "May" "June" "July"
     "August" "September" "October" "November" "December"))

(multiple-value-bind (sec min hour date month year day daylight-p zone) (get-decoded-time)

   (format t "~4d-~2,'0d-~2,'0d~%" year month date)
   (format t "~a, ~a ~d, ~4d~%" 
       (aref *day-names* day) (aref *month-names* month) date year))</lang>

D

Works with: D version DMD 1.026
Library: Tango

<lang d>module datetimedemo ;

import tango.time.Time ; import tango.text.locale.Locale ; import tango.time.chrono.Gregorian ;

import tango.io.Stdout ;

void main() {

   Gregorian g = new Gregorian ;
   Stdout.layout = new Locale; // enable Stdout to handle date/time format
   Time d = g.toTime(2007, 11, 10, 0, 0, 0, 0, g.AD_ERA) ;
   Stdout.format("{:yyy-MM-dd}", d).newline ;
   Stdout.format("{:dddd, MMMM d, yyy}", d).newline ;
   d = g.toTime(2008, 2, 1, 0, 0, 0, 0, g.AD_ERA) ;
   Stdout.format("{:dddd, MMMM d, yyy}", d).newline ;

}</lang> Sample Output:

2007-11-10
Saturday, November 10, 2007
Friday, February 1, 2008

Factor

<lang factor>USING: formatting calendar io ;

now "%Y-%m-%d" strftime print now "%A, %B %d, %Y" strftime print</lang>

Forth

<lang forth>: .-0 ( n -- n )

 [char] - emit
 dup 10 < if [char] 0 emit then ;
.short-date
 time&date ( s m h D M Y )
 1 u.r .-0 1 u.r .-0 1 u.r 
 drop drop drop ;
str-table
 create ( n -- ) 0 do , loop
 does>  ( n -- str len ) swap cells + @ count ;
here ," December"
here ," November"
here ," October"
here ," September"
here ," August"
here ," July"
here ," June"
here ," May"
here ," April"
here ," March"
here ," February"
here ," January"

12 str-table months

here ," Sunday"
here ," Saturday"
here ," Friday"
here ," Thursday"
here ," Wednesday"
here ," Tuesday"
here ," Monday"

7 str-table weekdays

\ Zeller's Congruence

zeller ( m -- days since March 1 )
 9 + 12 mod 1-   26 10 */ 3 + ;
weekday ( d m y -- 0..6 ) \ Monday..Sunday
 over 3 < if 1- then
 dup    4 /
 over 100 / -
 over 400 / +  +
 swap zeller + +
 1+ 7 mod ;
3dup dup 2over rot ;
.long-date
 time&date ( s m h D M Y )
 3dup weekday weekdays type ." , "
 >R 1- months type space 1 u.r ." , " R> .
 drop drop drop ;</lang>

Fortran

Works with: Fortran version 95 and later

The subroutine DATE_AND_TIME does not return day of week information so we have to write our own function for that <lang fortran>PROGRAM DATE

 IMPLICIT NONE
 
 INTEGER :: dateinfo(8), day
 CHARACTER(9) :: month, dayname
    
 CALL DATE_AND_TIME(VALUES=dateinfo)
 SELECT CASE(dateinfo(2))
   CASE(1)
     month = "January"
   CASE(2)
     month = "February"
   CASE(3)
     month = "March"
   CASE(4)
     month = "April"
   CASE(5)
     month = "May"
   CASE(6)
     month = "June"
   CASE(7)
     month = "July"
   CASE(8)
     month = "August"
   CASE(9)
     month = "September"
   CASE(10)
     month = "October"
   CASE(11)
     month = "November"
   CASE(12)
    month = "December"
 END SELECT
 day = Day_of_week(dateinfo(3), dateinfo(2), dateinfo(1))
 SELECT CASE(day)
   CASE(0)
     dayname = "Saturday"
   CASE(1)
     dayname = "Sunday"
   CASE(2)
     dayname = "Monday"
   CASE(3)
     dayname = "Tuesday"
   CASE(4)
     dayname = "Wednesday"
   CASE(5)
     dayname = "Thursday"
   CASE(6)
     dayname = "Friday"
 END SELECT
 
 WRITE(*,"(I0,A,I0,A,I0)") dateinfo(1),"-", dateinfo(2),"-", dateinfo(3)
 WRITE(*,"(4(A),I0,A,I0)") trim(dayname), ", ", trim(month), " ", dateinfo(3), ", ", dateinfo(1)

CONTAINS

 FUNCTION Day_of_week(d, m, y)
   INTEGER :: Day_of_week, j, k
   INTEGER, INTENT(IN) :: d, m, y
   
   j = y / 100
   k = MOD(y, 100)
   Day_of_week = MOD(d + (m+1)*26/10 + k + k/4 + j/4 + 5*j, 7)
 END FUNCTION Day_of_week

END PROGRAM DATE</lang> Output

2008-12-14
Sunday, December 14, 2008

F#

"F# Interactive" session:

> open System;;
> Console.WriteLine( DateTime.Now.ToString("yyyy-MM-dd") );;
2010-08-13
> Console.WriteLine( "{0:D}", DateTime.Now );;
Friday, August 13, 2010

Go

In an interesting design, you specify your format by providing the format for the date and time 01/02 03:04:05PM '06 -0700 <lang go>package main import "time" import "fmt"

func main() {

 fmt.Println(time.LocalTime().Format("2006-01-02"))
 fmt.Println(time.LocalTime().Format("Monday, January 2, 2006"))

}</lang>

Groovy

Solution: <lang groovy>def isoFormat = { date -> date.format("yyyy-MM-dd") } def longFormat = { date -> date.format("EEEE, MMMM dd, yyyy") }</lang>

Test Program: <lang groovy>def now = new Date() println isoFormat(now) println longFormat(now)</lang>

Haskell

<lang haskell>import Control.Monad import Data.Time import System.Locale

format1 :: FormatTime t => t -> String format1 = formatTime defaultTimeLocale "%Y-%m-%e"

format2 :: FormatTime t => t -> String format2 = formatTime defaultTimeLocale "%A, %B %d, %Y"

main = do

   t <- liftM2 utcToLocalTime getCurrentTimeZone getCurrentTime
   mapM_ putStrLn [format1 t, format2 t]</lang>

HicEst

<lang hicest> CHARACTER string*40

  WRITE(Text=string, Format='UCCYY-MM-DD') 0 ! string: 2010-03-13
  ! the U-format to write date and time uses ',' to separate additional output formats
  ! we therefore use ';' in this example and change it to ',' below:
  WRITE(Text=string,Format='UWWWWWWWWW; MM DD; CCYY') 0 ! string = "Saturday ; 03 13; 2010"
  READ(Text=string) month ! first numeric value = 3 (no literal month name available)
  EDIT(Text='January,February,March,April,May,June,July,August,September,October,November,December', ITeM=month, Parse=cMonth) ! cMonth = "March"
  ! change now string = "Saturday ; 03 13; 2010" to "Saturday, March 13, 2010":
  EDIT(Text=string, Right=' ', Mark1, Right=';', Right=3, Mark2, Delete, Insert=', '//cMonth, Right=';', RePLaceby=',')
END</lang>

J

Short format using built in formatting: <lang j> 6!:0 'YYYY-MM-DD' 2010-08-19</lang>

Verb to show custom format: <lang j>require 'dates system/packages/misc/datefmt.ijs' days=:;:'Sunday Monday Tuesday Wednesday Thursday Friday Saturday' fmtDate=: [:((days ;@{~ weekday),', ',ms0) 3 {.]

  fmtDate 6!:0 

Thursday, August 19, 2010</lang>

Java

<lang java>import java.util.Calendar; import java.util.GregorianCalendar; import java.text.DateFormatSymbols; import java.util.Date; import java.text.DateFormat; import java.text.SimpleDateFormat; public class Dates{ public static void main(String[] args){ Calendar now = new GregorianCalendar(); //months are 0 indexed, dates are 1 indexed DateFormatSymbols symbols = new DateFormatSymbols(); //names for our months and weekdays

//plain numbers way System.out.println(now.get(Calendar.YEAR) + "-" + (now.get(Calendar.MONTH) + 1) + "-" + now.get(Calendar.DATE));

//words way System.out.print(symbols.getWeekdays()[now.get(Calendar.DAY_OF_WEEK)] + ", "); System.out.print(symbols.getMonths()[now.get(Calendar.MONTH)] + " "); System.out.println(now.get(Calendar.DATE) + ", " + now.get(Calendar.YEAR));

//using DateFormat Date date = new Date(); DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd"); System.out.println(format1.format(date)); DateFormat format2 = new SimpleDateFormat("EEEE, MMMM dd, yyyy"); System.out.println(format2.format(date)); } }</lang>

JavaScript

JavaScript does not have any built-in strftime-type functionality. <lang javascript>var now = new Date();

var fmt1 = now.getFullYear() + '-' + (1 + now.getMonth()) + '-' + now.getDate(); print(fmt1);

var weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; var fmt2 = weekdays[now.getDay()] + ', ' + months[now.getMonth()] + ' ' + now.getDate() + ', ' + now.getFullYear(); print(fmt2);</lang>

2010-1-12
Tuesday, January 12, 2010

Liberty BASIC

<lang lb>'Display the current date in the formats of "2007-11-10" d$=date$("yyyy/mm/dd") print word$(d$,1,"/")+"-"+word$(d$,2,"/")+"-"+word$(d$,3,"/")

'and "Sunday, November 10, 2007". day$(0)="Tuesday" day$(1)="Wednesday" day$(2)="Thursday" day$(3)="Friday" day$(4)="Saturday" day$(5)="Sunday" day$(6)="Monday" theDay = date$("days") mod 7 print day$(theDay);", ";date$()

' month in full year=val(word$(d$,1,"/")) month=val(word$(d$,2,"/")) day=val(word$(d$,3,"/")) weekDay$="Tuesday Wednesday Thursday Friday Saturday Sunday Monday" monthLong$="January February March April May June July August September October November December"

print word$(weekDay$,theDay+1);", ";word$(monthLong$,month);" ";day;", ";year</lang>

Lua

<lang lua>print( os.date( "%Y-%m-%d" ) ) print( os.date( "%A, %B %d, %Y" ) )</lang>

Mathematica

<lang Mathematica>DateString[{"Year", "-", "Month", "-", "Day"}] DateString[{"DayName", ", ", "MonthName", " ", "Day", ", ", "Year"}]</lang>

MATLAB

<lang MATLAB>>> datestr(now,'yyyy-mm-dd')

ans =

2010-06-18

>> [datestr(now,'dddd, ') datestr(now,'mmmm dd, yyyy')]

ans =

Friday, June 18, 2010</lang>

MUMPS

Works with: Intersystems' Caché version (all versions)

Functions starting with 'Z' or '$Z' are implementation specific. <lang MUMPS>DTZ

WRITE !,"Date format 3: ",$ZDATE($H,3)
WRITE !,"Or ",$ZDATE($H,12),", ",$ZDATE($H,9)
QUIT</lang>

MUMPS contains the integer number of days since December 31, 1840 in the first part of the system variable $HOROLOG.

Works with: MUMPS version all

<lang MUMPS>DTM(H)

;You can pass an integer, but the default is to use today's value
SET:$DATA(H)=0 H=$HOROLOG
NEW Y,YR,RD,MC,MO,DA,MN,DN,DOW
SET MN="January,February,March,April,May,June,July,August,September,October,November,December"
SET DN="Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday"
SET MC="31,28,31,30,31,30,31,31,30,31,30,31"
SET Y=+H\365.25 ;This shouldn't be an approximation in production code
SET YR=Y+1841 ;Y is the offset from the epoch in years
SET RD=((+H-(Y*365.25))+1)\1 ;How far are we into the year?
SET $P(MC,",",2)=$S(((YR#4=0)&(YR#100'=0))!((YR#100=0)&(YR#400=0))=0:28,1:29) ;leap year correction
SET MO=1,RE=RD FOR  QUIT:RE<=$P(MC,",",MO)  SET RE=RE-$P(MC,",",MO),MO=MO+1
SET DA=RE+1
SET DOW=(H#7)+5 ;Fencepost issue - the first piece is 1
;add padding as needed
SET:$L(MO)<2 MO="0"_MO
SET:$L(DA)<2 DA="0"_DA
WRITE !,YR,"-",MO,"-",DA
WRITE !,$P(DN,",",DOW),", ",$P(MN,",",MO)," ",DA,", ",YR
KILL Y,YR,RD,MC,MO,DA,MN,DN,DOW
QUIT</lang>

Demos:

USER>D DTM^ROSETTA
 
2010-06-24
Thursday, June 24, 2010
USER>D DTM^ROSETTA(1234)
 
1844-05-19
Saturday, May 19, 1844
USER>D DTZ^ROSETTA
 
Date format 3: 2010-06-24
Or Thursday, June 24, 2010

Objective-C

<lang objc>NSLog(@"%@", [NSDate date]); NSLog(@"%@", [[NSDate date] descriptionWithCalendarFormat:@"%Y-%m-%d" timeZone:nil locale:nil]); NSLog(@"%@", [[NSDate date] descriptionWithCalendarFormat:@"%A, %B %d, %Y" timeZone:nil locale:nil]);</lang>

OCaml

<lang ocaml># #load "unix.cma";;

  1. open Unix;;
  1. let t = time() ;;

val t : float = 1219997516.

  1. let gmt = gmtime t ;;

val gmt : Unix.tm =

 {tm_sec = 56; tm_min = 11; tm_hour = 8; tm_mday = 29; tm_mon = 7;
  tm_year = 108; tm_wday = 5; tm_yday = 241; tm_isdst = false}
  1. Printf.sprintf "%d-%02d-%02d" (1900 + gmt.tm_year) (1 + gmt.tm_mon) gmt.tm_mday ;;

- : string = "2008-08-29"</lang>

<lang ocaml>let months = [| "January"; "February"; "March"; "April"; "May"; "June";

     "July"; "August"; "September"; "October"; "November"; "December" |] 

let days = [| "Sunday"; "Monday"; "Tuesday"; (* Sunday is 0 *)

     "Wednesday"; "Thursday"; "Friday"; "Saturday" |]
  1. Printf.sprintf "%s, %s %d, %d"
     days.(gmt.tm_wday)
     months.(gmt.tm_mon)
     gmt.tm_mday
     (1900 + gmt.tm_year) ;;

- : string = "Friday, August 29, 2008"</lang>

Oz

Getting the current local date is easy, but we have to do the formatting manually. <lang oz>declare

 WeekDays = unit(0:"Sunday" "Monday" "Tuesday" "Wednesday"
                 "Thursday" "Friday" "Saturday")
 Months = unit(0:"January" "February" "March" "April"
               "May" "June" "July" "August" "September"
               "October" "November" "December")
 fun {DateISO Time}
    Year = 1900 + Time.year
    Month = Time.mon + 1
 in
    Year#"-"#{Align Month}#"-"#{Align Time.mDay}
 end
 fun {DateLong Time}
    Year = 1900 + Time.year
 in
    WeekDays.(Time.wDay)#", "#Months.(Time.mon)#" "#Time.mDay#", "#Year
 end
 fun {Align Num}
    if Num < 10 then "0"#Num else Num end
 end

in

 {System.showInfo {DateISO {OS.localTime}}}
 {System.showInfo {DateLong {OS.localTime}}}</lang>

Pascal

Works with: Turbo Pascal version 5.5

<lang Pascal>program dateform; uses DOS;

{ Format digit with leading zero } function lz(w: word): string; var

 s: string;

begin

 str(w,s);
 if length(s) = 1 then
   s := '0' + s;
 lz := s

end;

function m2s(mon: integer): string; begin

 case mon of
    1: m2s := 'January';
    2: m2s := 'February';
    3: m2s := 'March';
    4: m2s := 'April';
    5: m2s := 'May';
    6: m2s := 'June';
    7: m2s := 'July';
    8: m2s := 'August';
    9: m2s := 'September';
   10: m2s := 'October';
   11: m2s := 'November';
   12: m2s := 'December'
 end

end;

function d2s(dow: integer): string; begin

 case dow of
   0: d2s := 'Sunday';
   1: d2s := 'Monday';
   2: d2s := 'Tueday';
   3: d2s := 'Wednesday';
   4: d2s := 'Thursday';
   5: d2s := 'Friday';
   6: d2s := 'Saturday'
 end

end;

var

 yr,mo,dy,dow: word;
 mname,dname: string;

begin

 GetDate(yr,mo,dy,dow);
 writeln(yr,'-',lz(mo),'-',lz(dy));
 mname := m2s(mo); dname := d2s(dow);
 writeln(dname,', ',mname,' ',dy,', ',yr)

end.</lang>

Output:

2010-07-30
Friday, July 30, 2010

Perl

Library: POSIX

<lang perl>use POSIX;

print strftime('%Y-%m-%d', 0, 0, 0, 10, 10, 107), "\n"; print strftime('%A, %B %d, %Y', 0, 0, 0, 10, 10, 107), "\n";</lang>

Output with locales C:

2007-11-10
Saturday, November 10, 2007

Output with locales cs_CZ.UTF-8:

2007-11-10
Sobota, listopad 10, 2007

Actual date: <lang perl>use POSIX;

print strftime('%Y-%m-%d', localtime), "\n"; print strftime('%A, %B %d, %Y', localtime), "\n";</lang>

Output with locales C:

2008-02-13
Wednesday, February 13, 2008

PHP

Formatting rules: http://www.php.net/date <lang php><?php echo date('Y-m-d', time())."\n"; echo date('l, F j, Y', time())."\n"; ?></lang>

PicoLisp

<lang PicoLisp>(let (Date (date) Lst (date Date))

  (prinl (dat$ Date "-"))             # 2010-02-19
  (prinl                              # Friday, February 19, 2010
     (day Date)
     ", "
     (get *MonFmt (cadr Lst))
     " "
     (caddr Lst)
     ", "
     (car Lst) ) )</lang>

PL/I

<lang PL/I>declare day_of_week(7) character (9) varying initial

  'Sunday', 'Monday', 'Tuesday', 'Wednesday',
  'Thursday', 'Friday', 'Saturday');

declare today character (8);

today = datetime('YYYYMMDD'); put edit (substr(today, 1, 4), '-', substr(today, 5, 2), '-', substr(today, 7) ) (A);

today = datetime('MmmDDYYYY');

put skip edit (day_of_week(weekday(days())), ', ') (A); put edit (substr(today, 1, 3), ' ', substr(today, 4, 2), ',', substr(today, 6, 4) ) (A);</lang>

PowerShell

<lang powershell>"{0:yyyy-MM-dd}" -f (Get-Date) "{0:dddd, MMMM d, yyyy}" -f (Get-Date)</lang> Note: The names of months and days follow the currently set locale but otherwise the format is unchanged.

PureBasic

Works with: PureBasic version 4.41

<lang PureBasic>;Declare Procedures Declare.s MonthInText() Declare.s DayInText()

Output the requested strings

Debug FormatDate("%yyyy-%mm-%dd", Date()) Debug DayInText() + ", " + MonthInText() + FormatDate(" %dd, %yyyy", Date())

Used procedures

Procedure.s DayInText()

 Protected d$
 Select DayOfWeek(Date())
   Case 1: d$="Monday"
   Case 2: d$="Tuesday"
   Case 3: d$="Wednesday"
   Case 4: d$="Thursday"
   Case 5: d$="Friday"
   Case 6: d$="Saturday"
   Default: d$="Sunday"
 EndSelect
 ProcedureReturn d$

EndProcedure

Procedure.s MonthInText()

 Protected  m$
 Select Month(Date())  
   Case 1: m$="January"
   Case 2: m$="February"
   Case 3: m$="March"
   Case 4: m$="April"
   Case 5: m$="May"
   Case 6: m$="June"
   Case 7: m$="July"
   Case 8: m$="August"
   Case 9: m$="September"
   Case 10:m$="October"
   Case 11:m$="November"
   Default:m$="December"
 EndSelect
 ProcedureReturn m$

EndProcedure</lang>

Python

Formatting rules: http://docs.python.org/lib/module-time.html (strftime)

<lang python>import datetime today = datetime.date.today()

  1. This one is built in:

print today.isoformat()

  1. Or use a format string for full flexibility:

print today.strftime('%Y-%m-%d')</lang>

R

strftime is short for "string format time". <lang R>now <- Sys.time() strftime(now, "%Y-%m-%d") strftime(now, "%A, %B %d, %Y")</lang>

Raven

<lang raven>time int as today</lang>

Short form:

<lang raven>today '%Y-%m-%d' date</lang>

Long form:

<lang raven>today '%A, %B %d, %Y' date</lang>

REBOL

<lang REBOL>REBOL [ Title: "Date Formatting" Author: oofoe Date: 2009-12-06 URL: http://rosettacode.org/wiki/Date_format ]

REBOL has no built-in pictured output.

zeropad: func [pad n][

   n: to-string n
   insert/dup n "0" (pad - length? n)
   n 

] d02: func [n][zeropad 2 n]

print now ; Native formatting.

print rejoin [now/year "-" d02 now/month "-" d02 now/day]

print rejoin [ pick system/locale/days now/weekday ", " pick system/locale/months now/month " " now/day ", " now/year ]</lang>

Output:

6-Dec-2009/10:02:10-5:00
2009-12-06
Sunday, December 6, 2009

REXX

<lang REXX>/*show current date in yyyy-mm-dd and also Dayofweek, Month dd, yyyy*/ x=date('s') /* yyyymmdd */ yyyy=left(x,4) /* pick off the year. */ dd=right(x,2) /* pick off the day of month */ say yyyy'-'substr(x,5,2)"-"dd /*yyyy-mm-dd with leading 0s */

weekday =date('w') /* Dayofweek (Saturday) */ month =date('m') /* Month (December) */ zdd =dd+0 /* remove leading zero of DD */ say weekday',' month zdd"," yyyy /*Month dd, yyyy */</lang> Output:

2010-09-01
Wednesday, September 1, 2010 

<==Ruby== Formatting rules: http://www.ruby-doc.org/core/classes/Time.html#M000297 (strftime)

<lang ruby>puts Time.now puts Time.now.strftime('%Y-%m-%d') puts Time.now.strftime('%A, %B %d, %Y')</lang> Output:

Wed Feb 13 14:24:38 -0800 2008
2008-02-13
Wednesday, February 13, 2008

Scala

<lang scala>val now=new Date() println("%tF".format(now)) println("%1$tA, %1$tB %1$td, %1$tY".format(now))</lang>

Standard ML

Formatting rules: http://www.standardml.org/Basis/date.html#SIG:DATE.fmt:VAL

<lang sml>print (Date.fmt "%Y-%m-%d" (Date.fromTimeLocal (Time.now ())) ^ "\n"); print (Date.fmt "%A, %B %d, %Y" (Date.fromTimeLocal (Time.now ())) ^ "\n");</lang> Output:

2008-02-13
Wednesday, February 13, 2008

Suneido

<lang Suneido>Date().Format('yyyy-MM-dd') --> "2010-03-16" Date().LongDate() --> "Tuesday, March 16, 2010" </lang>

Tcl

<lang tcl>set now [clock seconds] puts [clock format $now -format "%Y-%m-%d"] puts [clock format $now -format "%A, %B %d, %Y"]</lang>

TUSCRIPT

<lang tuscript> $$ MODE TUSCRIPT SET dayofweek = DATE (today,day,month,year,number)

SET months=* DATA January DATA Februari DATA March DATA April DATA Mai DATA June DATA July DATA August DATA September DATA October DATA November DATA December

SET days="Monday'Tuesday'Wendsday'Thursday'Fryday'Saturday'Sonday"

SET nameofday =SELECT (days,^#dayofweek) SET nameofmonth=SELECT (months,^#month)

SET format1=JOIN (year,"-",month,day) SET format2=CONCAT (nameofday,", ",nameofmonth," ",day, ", ",year)

PRINT format1 PRINT format2 </lang>

UNIX Shell

<lang bash>date +"%Y-%m-%d" date +"%A, %B %d, %Y"</lang>

Ursala

The method is to transform a date in standard format returned by the library function, now. <lang Ursala>#import std

  1. import cli

months = ~&p/block3'JanFebMarAprMayJunJulAugSepOctNovDec' block2'010203040506070809101112'

completion =

-:~& ~&pllrTXS/block3'SunMonTueWedThuFriSat'--(~&lS months) -- (

  --','* sep`, 'day,day,sday,nesday,rsday,day,urday',
  sep`, 'uary,ruary,ch,il,,e,y,ust,tember,ober,ember,ember')

text_form = sep` ; mat` + completion*+ <.~&hy,~&tth,--','@th,~&ttth> numeric_form = sep` ; mat`-+ <.~&ttth,@tth -: months,~&th>

  1. show+

main = <.text_form,numeric_form> now0</lang> output:

Wednesday, June 24, 2009
2009-06-24

Vedit macro language

Display current date in format "2007-11-10":

<lang vedit>Date(REVERSE+NOMSG+VALUE, '-')</lang>

Display current date in format "Sunday, November 10, 2007": <lang vedit>// Get todays date into #1, #2 and #3 Buf_Switch(Buf_Free) Out_Ins() Date(BEGIN+NOMSG) Out_Ins(CLEAR) BOF

  1. 1 = Num_Eval(SUPPRESS+ADVANCE) // #1 = day

Char

  1. 2 = Num_Eval(SUPPRESS+ADVANCE) // #2 = month

Char

  1. 3 = Num_Eval(SUPPRESS) // #3 = year

Buf_Quit(OK)

  1. 7 = JDate() % 7 // #7 = weekday

// Convert weekday number (in #7) into word in T-reg 1 if (#7==0) { RS(1,"Sunday") } if (#7==1) { RS(1,"Monday") } if (#7==2) { RS(1,"Tuesday") } if (#7==3) { RS(1,"Wednesday") } if (#7==4) { RS(1,"Thursday") } if (#7==5) { RS(1,"Friday") } if (#7==6) { RS(1,"Saturday") }

// Convert month number (in #2) into word in T-reg 2 if (#2==1) { RS(2,"January") } if (#2==2) { RS(2,"February") } if (#2==3) { RS(2,"March") } if (#2==4) { RS(2,"April") } if (#2==5) { RS(2,"May") } if (#2==6) { RS(2,"June") } if (#2==7) { RS(2,"July") } if (#2==8) { RS(2,"August") } if (#2==9) { RS(2,"September") } if (#2==10) { RS(2,"October") } if (#2==11) { RS(2,"November") } if (#2==12) { RS(2,"December") }

// Display the date string RT(1) M(", ") RT(2) M(" ") NT(#1, LEFT+NOCR) M(",") NT(#3)</lang>

To insert the date string into edit buffer instead of displaying it, replace the last line with this:

<lang vedit>RI(1) IT(", ") RI(2) IT(" ") NI(#1, LEFT+NOCR) IT(",") NI(#3)</lang>