How to show Unix time in C?

J

Jirka Klaue

I'm trying to show current Unix time in C.
Is it possible?

It depends on what you mean by "Unix time".

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

int main()
{
time_t t = time(0);
printf(ctime(&t));
return 0;
}

Jirka
 
T

Thomas Cameron

<posted & mailed>

I'm trying to show current Unix time in C.

Is it possible?

The following creates the time structure you need, and populates its
elements with the current system values.

struct timeval tv;
gettimeofday(&tv, NULL);

Now, you can printf any elements you choose:
printf("Sec: %d uSec: %d\n", tv.tv_sec, tv.tv_usec)

That should do. Just look up the manpage for any other elements, etc.
 
K

Keith Thompson

I'm trying to show current Unix time in C.

Is it possible?

If by "Unix time", you mean a raw time_t value, there's not a whole
lot you can do with it portably. The standard only guarantees that
it's an arithmetic type capable of representing times.

The following might do something useful:

#include <stdio.h>
#include <time.h>
int main()
{
printf("%ld\n", (long)time(NULL));
return 0;
}

If time_t is a floating-point type whose value is always between 0.0
and 1.0, you won't get much useful information from this. If it's,
say, an integer type representing the whole number of seconds since
1970-01-01 00:00:00 GMT, the result might be meaningful (as I write
this, it's 1112465716). <OT>The latter happens to be the
representation of time_t on Unix and some other systems, but of course
such implementation details are off-topic here.</OT>

If you want to display a legible and portable representation of the
current time, you can use something like this:

#include <stdio.h>
#include <time.h>
int main()
{
time_t now;
time(&now);
fputs(ctime(&now), stdout);
return 0;
}
 
I

invincible

hi

this would help u

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

#define SIZE 256

int
main (void)
{
char buffer[SIZE];
time_t curtime;
struct tm *loctime;

/* Get the current time. */
curtime = time (NULL);

/* Convert it to local time representation. */
loctime = localtime (&curtime);

/* Print out the date and time in the standard format. */
fputs (asctime (loctime), stdout);

/* Print it out in a nice format. */
strftime (buffer, SIZE, "Today is %A, %B %d.\n", loctime);
fputs (buffer, stdout);
strftime (buffer, SIZE, "The time is %I:%M %p.\n", loctime);
fputs (buffer, stdout);

return 0;
}

It produces output like this

Wed Jul 31 13:02:36 1991
Today is Wednesday, July 31.
The time is 01:02 PM.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,161
Messages
2,570,892
Members
47,428
Latest member
RosalieQui

Latest Threads

Top