0

Hye there, this code will output date and time. But I have trouble when I wanted it to display the time with milliseconds.

char *time()
{

    const struct tm *tm;
    size_t len;
    time_t now;
    char *s;

    now = time ( NULL );
    tm = localtime ( &now );

    s = ( char * ) malloc ( TIME_SIZE * sizeof ( char ) );

    len = strftime ( s, TIME_SIZE, "%Y %m %d %H:%M:%S.", tm );

    return s;

}
The Head Rush
  • 3,157
  • 2
  • 25
  • 45
frescoF
  • 1
  • 1
  • What is the specific issue you have displaying the millis? – The Head Rush May 16 '18 at 14:00
  • 1
    You can’t call your function `time()` and then call the standard function `time()` unless you’re using C++ and an overload. You need to call a function that gives you fractions of a second; which platform are you on? And `strftime()` does not format sub-second values so you’ll have to handle that part. – Jonathan Leffler May 16 '18 at 14:03
  • I'm doing C programming – frescoF May 16 '18 at 14:06
  • @frescoF; OK, then the code is invalid - fix it, otherwise all you will get is noise about the broken code rather then the answer you seek. – Clifford May 16 '18 at 14:22
  • Note that the duplicate question ([Get millisecond part of time](https://stackoverflow.com/questions/10654258/get-millisecond-part-of-time)) is primarily for C++. The answers are not comprehensive for C — it doesn't mention POSIX [`clock_gettime()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/clock_gettime.html) which is the preferred subsecond time of day interface for POSIX systems, for example, and doesn't cover interfaces such as [`ftime()`](http://pubs.opengroup.org/onlinepubs/7990989775/xsh/ftime.html) which was in SUS 1997 but is now obsolete (but often still available). – Jonathan Leffler May 16 '18 at 14:32
  • @JonathanLeffler : It is tagged C++, but the code and the answer are (also) valid C code. Point taken re `clock_gettime(). It may be useful to re-open this an post an answer. – Clifford May 18 '18 at 07:37
  • @Clifford: Just because an answer happens to be valid in another programming language, does not make it the *correct* one. Here, POSIX.1 `clock_gettime()` is the correct answer. The standard C library provides wall-clock time at one-second precision only; the second most relevant standard being POSIX.1. I am aggravated, because I cannot re-open or vote this question for re-opening/unlinking, and cannot post an answer explaining the situation and the solutions, because of *your actions*. – Nominal Animal May 18 '18 at 12:55

0 Answers0