Date format: Difference between revisions
m (→[[Date_format#ALGOL 68]]: tidy.) |
(→{{header|Vedit macro language}}: Fix: avoid negative numerator in modulo calculation) |
||
Line 538: | Line 538: | ||
#4 = #13 % 100 |
#4 = #13 % 100 |
||
#5 = #13 / 100 |
#5 = #13 / 100 |
||
#7 = (#1 + (#12+1)*26/10 + #4 + #4/4 + #5/4 |
#7 = (#1 + (#12+1)*26/10 + #4 + #4/4 + #5/4 + #5*5) % 7 |
||
// Convert weekday number (in #7) into word in T-reg 1 |
// Convert weekday number (in #7) into word in T-reg 1 |
Revision as of 16:08, 5 May 2009
You are encouraged to solve this task according to the task description, using any language you may know.
Display the current date in the formats of "2007-11-10" and "Sunday, November 10, 2007".
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
Note: the format can be used for both printing and reading date data.
<lang algol>
- 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
BASIC
<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>
- include <stdlib.h>
- include <time.h>
int main() {
time_t seconds; struct tm *now; seconds = time(NULL); now = localtime(&seconds); printf("%d-%d-%d\n", now->tm_year + 1900, now->tm_mon + 1, now->tm_mday); char *months[] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; 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);
/* shortcut for default format */ printf("%s", ctime(&seconds));
return 0;
} </lang> Sample output:
2008-10-7 Tuesday, October 7, 2008 Tue Oct 7 16:51:40 2008
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>
ColdFusion
<cfset date = createDate( 2007, 11, 10 ) /> #dateFormat( date, "YYYY-MM-DD" )#, #dateFormat( date, "DDDD, MMMM DD, YYYY" )#
D
<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
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 ;
Fortran
The subroutine DATE_AND_TIME does not return day of week information so we have to write our own function for that
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
Output
2008-12-14 Sunday, December 14, 2008
Haskell
<lang haskell>import System.Locale import System.Time
format1 :: CalendarTime -> String format1 = formatCalendarTime defaultTimeLocale "%Y-%m-%e"
format2 :: CalendarTime -> String format2 = formatCalendarTime defaultTimeLocale "%A, %B %d, %Y"
main = do
t <- getClockTime >>= toCalendarTime mapM_ putStrLn [format1 t, format2 t]</lang>
J
dayNm =: ;:'Sunday Monday Tuesday Wednesday Thursday Friday Saturday' monthNm=: ;:'0 January February March April May June July August September October November December' dateFormat=: 3 : 0 0 dateFormat y NB. default to short format : 'year month date'=. 3{. y select. x case. 0 do. NB. short format YYYY-MM-DD, e.g. '1900-02-28' dashNN=. (('-0' {.~ (3-#)) ,])@ ": (":year),(dashNN month),(dashNN date) case. 1 do. NB. verbose format, e.g. 'Wednesday, February 28, 1900' Y=. year - A =. <. 12%~ 14-month M=. <.12%~31*(month+12*A)-2 D=. 7| date+M+Y+(<.Y%4)+(<.Y%400)-(<.Y%100) (>D{dayNm), ', ',(>month{monthNm),' ',(":date), ', ', ":year end. )
Example:
(dateFormat ,: 1& dateFormat) 1920 12 17 1920-12-17 Friday, December 17, 1920
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>
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";;
- open Unix;;
- let t = time() ;;
val t : float = 1219997516.
- 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}
- 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" |]
- 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>
Perl
<lang perl>use POSIX;
print POSIX::strftime('%Y-%m-%d', 0, 0, 0, 10, 10, 107), "\n"; print POSIX::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 POSIX::strftime('%Y-%m-%d', localtime), "\n"; print POSIX::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>
Python
Formatting rules: http://docs.python.org/lib/module-time.html (strftime)
<lang python>import datetime today = datetime.date.today()
- This one is built in:
print today.isoformat()
- Or use a format string for full flexibility:
print today.strftime('%Y-%m-%d')</lang>
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
Raven
time int as today
Short form:
today '%Y-%m-%d' date
Long form:
today '%A, %B %d, %Y' date
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
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>
UNIX Shell
date +"%Y-%m-%d" date +"%A, %B %d, %Y"
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 = Num_Eval(SUPPRESS+ADVANCE) // #1 = day
Char
- 2 = Num_Eval(SUPPRESS+ADVANCE) // #2 = month
Char
- 3 = Num_Eval(SUPPRESS) // #3 = year
Buf_Quit(OK)
// Calculate weekday using Zeller's congruence
- 12 = #2 // month tmp
- 13 = #3 // year tmp
if (#12 < 3) {
#12 += 12 #13--
}
- 4 = #13 % 100
- 5 = #13 / 100
- 7 = (#1 + (#12+1)*26/10 + #4 + #4/4 + #5/4 + #5*5) % 7
// Convert weekday number (in #7) into word in T-reg 1 if (#7==0) { RS(1,"Saturday") } if (#7==1) { RS(1,"Sunday") } if (#7==2) { RS(1,"Monday") } if (#7==3) { RS(1,"Tuesday") } if (#7==4) { RS(1,"Wednesday") } if (#7==5) { RS(1,"Thursday") } if (#7==6) { RS(1,"Friday") }
// 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>
- Programming Tasks
- Text processing
- Clarified and Needing Review
- Ada
- ALGOL 68
- BASIC
- C
- C sharp
- ColdFusion
- ColdFusion examples needing attention
- Examples needing attention
- D
- D examples needing attention
- Tango
- Forth
- Fortran
- Haskell
- J
- Java
- Objective-C
- OCaml
- Perl
- POSIX
- PHP
- Python
- Ruby
- Raven
- Standard ML
- Tcl
- UNIX Shell
- Vedit macro language