Date: 2008feb10
Platform: Linux, win32
Language: C/C++, Perl, PHP
Q. 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)
{
const 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 is cleaner
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());
}
?>