How can I cause the datetime to be the name of the output file.....

A

Al Balmer

One snag is that the American convention (9/11) is different to the British
(11/9). In my opinion months should always include the name, to avoid
confusion.
Usually there are other considerations more important than
readability. Sorting, for example, where you probably want
YYYYMMDDhhmm.
 
J

Joe Wright

Keith said:
For what it's worth..

/* DateTime in C */
#include <stdio.h>
#include <time.h>

int main(void) {
struct tm tm;
char buf[15];
time_t tim = time(0);
tm = *localtime(&tim);
strftime(buf, sizeof buf, "%Y%m%d%H%M%S", &tm);
puts(buf);
return 0;
}

The Unix/C time stuff does seem cumbersome to me.


Just to be clear, does "Unix/C time stuff" refer to the code you
posted? Everything in your program is standard C; there's nothing
Unix-specific about it. (Yes, Unix and C are historically
intertwined; perhaps that's what you meant, but the C standards try to
disentangle them, even while standardizing features that originated
under Unix.)

The output of the program is, for example:
20060205143135
For legibility, I'd change the format string to
"%Y-%m-%d %H:%M:%S"
resulting in
2006-02-05 14:31:35
Or, if I needed to use the result as part of a file name, I might use
"%Y-%m-%d-%H%M%S"
resulting in
2006-02-05-143135
(':' and ' ' characters in file names cause problems on the systems I
use; which characters are allowed in file names is, of course,
entirely system-specific. There may be length constraints as well.)

See also strftime's "%F" conversion specifier, equivalent to
"%Y-%m-%d", and "%T", equivalent to "%H:%M:%S".

A side note: when I started modifying your code, I initially forgot to
change the size of the buffer. I was lucky enough to get some
odd-looking output. This is an illustration of why magic numbers are
a bad idea. If the length of the buffer had been a macro, I would
have been more likely to notice it.
Thanks for the critique. The code was meant to be one example to how to
do it. The code is correct as far as I know and is a valid example.

The format string does exactly what I want. I think %F might be C99
specific. I start with C89.
 

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

Staff online

Members online

Forum statistics

Threads
474,175
Messages
2,570,942
Members
47,489
Latest member
BrigidaD91

Latest Threads

Top