Dave's Brain

Browse - Programming Tips - What's the best way to get the current date as YYYY.MM.DD

Date: 2008feb10
Platform: Linux, win32
Language: C/C++, Perl, PHP

Q.  What's the best way to get the current date as YYYY.MM.DD 
in several languages?

A.  There are typically several ways to do this.  The ways described
here are what I believe are the safest, simplest and fastest.

// In standard C/C++ #include <time.h> void get_current_date(char *buf, const size_t size) { time_t now = time(NULL); struct tm here; localtime_r(&now, &here); strftime(buf, size, "%Y.%m.%d", &here); }
// In Win32 C/C++ the above function will work but this seems better void GetCurrentDate(LPSTR buf, const size_t size) { SYSTEMTIME now; GetLocalTime(&now); _snprintf(buf, size, "%04d.%02d.%02d", now.wYear, now.wMonth, now.wDay); }
# In Perl sub getCurrentDate() { my(@tm, $year, $mon, $mday); @tm = localtime(time()); $year = $tm[5] + 1900; $mon = $tm[4] + 1; $mday = $tm[3]; return sprintf('%04d.%02d.%02d', $year, $mon, $mday); # Perl's POSIX module has a strtime() but only small number of lines # of code avoids pulling in that big module }
<? # In PHP # Can not call it "getdate()" because that name is already taken function getCurrentDate() { return date('Y.m.d', time()); } ?>

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.