Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Displaying Current Date in C program

Status
Not open for further replies.

Ambatim

Programmer
Feb 28, 2002
110
IN
Hello All,

How to display the current date in a C program.
I know that date command in Unix displays the current date. But how to get that in a C variable and print it in a C program

Thanks in advance

Regards
Mallik
 
Use the date/time struct tm
ie
long now;
struct tm *tmstruct, *localtime();
time(&now);
tmstruct = localtime(&now);
printf("%02d/%02d/%04d", tmstruct->tm_mday,tmstruct->tm_mon,tmstruct->tm_year);
 
Hello Dickiebird,

Thank you for your reply.

What the statement time(&now) means. You are not using it anywhere else in the code.

Thanks

Regards
Mallik
 
Sorry - Spurious line
I cut and pasted the code segment from an old program of mine, and left in some unnecessaries
DB
 
with the tm struct you can use the strftime function to format the output.

Code:
#include <stdio.h>
#include <time.h>

time_t t_now;
struct tm *tm_now;

t_now = time(NULL);
tm_now = localtime(&t_now);

char time_buf[50];

strftime(time_buf,50,&quot;%d/%m/%Y %H:%M:%S&quot;,tm_now);

printf(&quot;%s\n&quot;,time_buf);

---- output
25/03/2002 11:44:14
-------------------


bluenote@clorinda.dnsq.org
(excuse my english)
 
All kinds of ways (how do you think the &quot;date&quot;
command works?)

Anyway, you also have &quot;asctime()&quot;...

SYNOPSIS
#include <time.h>

char *asctime(const struct tm *timeptr);

DESCRIPTION
The asctime() function converts the broken-down time in the
structure pointed to by timeptr into a string in the form:

Sun Sep 16 01:03:52 1973\n\0
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top