The end of the year 2010 is near so I’ve prepared this post for all you coders, developers and other geeks. You know when you build applications (especially web applications) you often leave a copyright notice on every page saying “Copyright 2010, All Rights Reserved” or whatever? Right, but what developers tend to forget is that time passes by and that they have to go back and change 2010 to 2011 in January — so we often browse websites, especially in January and February that have last year’s copyrights.
The best trick is not to hardcode the year inside your templates and skins, but to write the current year dynamically using date functions, so below is a list of printing out the current year in 10 different programming languages.
- Python
- PHP
- C/C++
- JavaScript
- Perl
- Ruby
- Java
- Unix Shell
- Go (golang)
- x86 Assembly (no kidding)
And here’s a list of ones contributed by commentators:
Python
from datetime import date print date.today().year
PHP
Definitely one of the easiest ways.
echo date("Y");
C and C++
#include <stdio.h> #include <time.h> int main() { time_t now = time(NULL); struct tm* local = localtime(&now); printf("%d", local->tm_year + 1900); return 0; }
JavaScript
document.write(new Date().getFullYear());
Perl
my $year = (localtime)[5]; print $year + 1900;
Ruby
puts Time.now.year
Java
import java.util.*; import java.text.*; public class Apollo { public static void main(String[] args) { Date date = new Date(); SimpleDateFormat simpleDateformat=new SimpleDateFormat("yyyy"); System.out.println(simpleDateformat.format(date)); } }
Unix Shell
Seems to be the shortest one of all.
date +%Y
Go (golang)
Interesting fact that when I ran this code on the Go website I ended up with 2009 — guess their servers are running a little slow?
package main import ("fmt" "time") func main() { var t = time.LocalTime() fmt.Println(t.Year) }
x86 Assembly
Here’s a special one, donated by my brother @SoulSeekah.
jmp start year db "0000$" start: mov ah, 04h int 1Ah mov bh, ch shr bh,4 add bh,30h mov [year], bh mov bh,ch and bh,0fh add bh,30h mov [year+1],bh mov bh, cl shr bh,4 add bh,30h mov [year+2], bh mov bh,cl and bh,0fh add bh,30h mov [year+3],bh mov ah,09h mov dx, offset year int 21h mov ah,4Ch mov al,00 int 21h
Lua
Code by Vesa Marttila (@ponzao).
print(os.date("*t").year)
Clojure
Once again thanks to Vesa Marttila (@ponzao).
(let [date (java.util.Date.) sdf (java.text.SimpleDateFormat. "yyyy")] (println (.format sdf date)))
Objective-C
Donated by Lowell via the comments section.
#import <Foundation/Foundation.h> int main (int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; NSLog (@"%d", [[NSCalendarDate date] yearOfCommonEra]); [pool drain]; return 0; }
C# (C-Sharp)
Contributed by a certain Paul via the comments.
using System; class Program { static void Main(string[] args) { Console.WriteLine(DateTime.Now.Year); } }
Tcl
Contributed by Robert.
set year [clock format [clock seconds] -format {%Y}] puts $year
Adobe Flex
Seems to work with both Flex 3 and 4, contributed by Uber_Nick via reddit.com comments.
<?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"> <mx:Label text="{new Date().fullYear}" /> </mx:Application>
Delphi
Thanks to Rejn via comments and Reddit.
ShowMessage( IntToStr(YearOf(Now)) );
Haskell
Thanks to Pezezin via comments and Onmach via Reddit.
import System.Time main = getClockTime >>= toCalendarTime >>= print . ctYear
Oh, and here’s a special one in LOLCODE by Danita via Reddit.
That’s about it! Feel free to contribute to the list in any other programming language, preferably well-known and easy to test. Use pastebin.com and leave links to your code in the comments section below. Have a Merry Christmas and a Happy New Year. Welcome to twenty-eleven! See you next year! Oh, and thank you all for tweeting this!
P.S. Christmas is on January 7th in Russia, so we’re not going to have holidays until the 31st.
[…] This post was mentioned on Twitter by Konstantin Kovshenin and others. Konstantin Kovshenin said: RT @teylorfeliz: Happy 2011: In 10 Different Programming Languages https://konstantin.blog/2905 (via @kovshenin) […]
Clojure: http://pastebin.com/uiRrRhT9
Lua: http://pastebin.com/yNmmyK62
Thanks so much Vesa, I've added your codes to the post. Have a great New Year!
You're welcome! I wish you a great New Year too!
BrainFuck: http://pastebin.com/nvLPjbrr
Seriously Reuben, you gotta do better than this :) Brainfuck is cool, I have no issues against it, but simply printing 2011 on screen is not cool. Remember I mentioned in the beginning of this post that the reason I'm writing it is 'cause lot of people hard-code copyright dates?
Thanks for your commitment anyway ;) I had fun testing your code.
Bored. Objective-C: http://pastie.org/1408527
Thanks! You might want to mention your Twitter account so I could give you credit ;)
No worries.
Oh yeah, I changed it into a one-liner. Same URI.
Note that the following is also valid Objective-C. If you compile with -fobjc-gc, the garbage collector will be enabled (does not work on iOS AFAIK).
#import
int main (int argc, const char * argv[]) {
NSLog (@"%d", [[NSCalendarDate date] yearOfCommonEra]);
return 0;
}
For Ruby:
puts Time.new.year
Is sufficient.
better yet: puts Time.now.year : note the 'now' :P
Thanks guys, makes sense ;)
Perl:
my $year = (localtime)[5];
print $year + 1900;
You forgot (or it got stripped) the last semi-colon…
Thanks Robert, edited the code. The one-liner below didn't work for some reason which is why I used your simplified version.
Oh and I like Tcl:
set year [clock format [clock seconds] -format {%Y}]
puts $year
Thanks Robert, put your code up in the post, you can tell me your Twitter name so I can leave credit ;)
C#: http://pastebin.com/6k05NGMS
Thank you sir, you've been listed! ;)
in REBOL
REBOL [] ;; standard header
print now/year
Your UNIX Shell example is much too long. Correct is:
date +%Y
which makes it the shortest of all the ones here.
And your Perl example could be:
print (localtime)[5] + 1900;
Thanks Joshua, although the Perl one-liner didn't work gave a syntax error so I had to simplify the two-liner. Don't know why, I'm not a perl programmer ;)
Cheers!
Dear readers! If you're contributing code, don't hesitate to mention your Twitter name so I can give you credit in the post ;)
Cheers!
java:
System.out.println(java.util.Calendar.getInstance().get(java.util.Calendar.YEAR));
What? No SQL?
SELECT YEAR(GETDATE()) as "Year";
Haskell, just two lines:
import System.Time
main = getClockTime >>= toCalendarTime >>= print . ctYear
Thanks, I've updated the post to include your code.
The JavaScript example shouldn't really be wrapped in the 'document.write' function. That's part of a web-browsers DOM, rather than JavaScript itself.
So what do you think is the best way to actually output it on screen? I'm sort of trying to keep the same pattern for all the snippets, they output something on screen :)
Much simpler java version. No imports needed:
public class Happy {
public static void main(String[] args) {
System.out.printf("%Y
", System.currentTimeMillis());
}
}
I get an exception: Exception in thread "main" java.util.UnknownFormatConversionException: Conversion = 'Y'
(java version "1.6.0_20")
Delphi
ShowMessage( IntToStr(YearOf(Now)) );
Common Lisp : (ql:quickload "local-time") (local-time:timestamp-year (local-time:now))
Or with no libraries required:
(sixth (multiple-value-list (get-decoded-time)))
@grimatongueworm
SQL is not a programming language, but rather, as the name implies, a query language.
ANS Forth:
time&date . bye
enjoy the Clojure version:
http://pastebin.com/z8BnHbvn
the ABAP one:
http://pastebin.com/GHN3EPJv
and the groovy one:
http://pastebin.com/xQG612ZM
#lang racket
(require racket/date)
(date-year (current-date))
Io Language:
Io> Date year
==> 2010
in Css:
body:after{
content:"happy new year 2011";
}
in oracle pl/sql:
select extract(year from sysdate)
from dual
in Css:
body:after{
content:'happy new year 2011'; // edited one quotation
}
in oracle pl/sql:
select extract(year from sysdate)
from dual
Date goodness in Rexx
substr(date('S',1,4))
Prolog:
get_time(T), stamp_date_time(T, date(_, _, _, H, M, S, _, _, _), 'UTC').
sorry it should have been:
get_time(T), stamp_date_time(T, date(Y, _, _, _, _, _, _, _, _), ‘UTC’).
Ruby beats them all
SQL
select year(getdate())
// D
import std.stdio, std.date;
void main(string[] args)
{
writeln(yearFromTime(UTCtoLocalTime(getUTCtime())));
}
Here's an old one in QBasic :-)
http://pastebin.com/r5G4hrwr
Don't curse on me but here's one I didn't find here yet, so:
The year in VBScript :-)
http://pastebin.com/nRnsPgNc
Make it a one-liner in Perl:
print((localtime)[5] + 1900);
In erlang:
{{Year, _, _}, _} = erlang:localtime().
io:format("~w~n", [Year]).
Oh, apparently this can be a little more concise:
{Year, _, _} = erlang:date().
io:format("~w~n", [Year]).
Here a solution invoking the Scala Interpreter:
scala -e 'printf("%TY
", System.currentTimeMillis)'
Since the other examples do omit the compiler/interpreter commands, the scala example becomes simply this:
printf("%TY
", System.currentTimeMillis)
It's a one-liner in REXX:
SAY WORD(DATE(),3)
chevere los tipos diferentes de lenguajes. falto jsp. aspx . etc
groovier groovy
println new Date().format('yyyy')
I think the Java version is a bit too long. How about :
public class HappyNewYear {
public static void main(String[] args) {
System.out.println(new java.util.GregorianCalendar().get(java.util.Calendar.YEAR));
}
}
Or how about CSS?
#year:before{content:"2011";}
<code>
#year:before{content:"2011";}
</code>
<style type="text/css">
#year:before{content:"2011";}
</style>
<div id="year"></div>
PowerShell
(Get-Date).Year
Here the Code for Realbasic
dim d as new date
MsgBox str(d.Year)
Abap
=================
write sy-datum(4).
================
MSSQL
select year(getdate())