create your own time stamp 2

From my previous post, create your own time stamp, I have introduced a way to construct your own time stamp.

Recently I found a better way, and with this function, you can create a better time stamp, yet the way of construct the time stamp is far more simple compared to my previous post.

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

int main()
{
    char timestamp[100];
    time_t mytime;
    struct tm *mytm;
    mytime=time(NULL);
    mytm=localtime(&mytime);

    strftime(timestamp,sizeof timestamp,"%a, %d %b %Y %H:%M:%S %z",mytm);

    printf("%s\n",timestamp);

    return 0;
}

Yes, that’s it, and the output is show as below:

Wed, 26 Sep 2007 23:54:50 +0800

5 thoughts on “create your own time stamp 2

  1. Nice example. But i get warnings on its compilation:
    warning: assignment makes pointer from integer without a cast
    warning: incompatible implicit declaration of built-in function ‘strftime’.

    GCC version is gcc (GCC) 4.1.1 (Gentoo 4.1.1-r1 p1.7.1).

    What is wrong?

  2. it’s most probably due to a cast problem.
    The strftime’s prototype is :
    size_t strftime(char *s, size_t maxsize, const char *format, const struct tm *timptr);

    Hope this will help.

  3. This example is good, but i want display milliseconds along with this.
    pls send me the code for displating Date – Hr:Min:Sec:Milliseconds format.

  4. Great CODE mate.. Sadly on building this i get an error: warning C4996: ‘localtime’: This function or variable may be unsafe. Consider using localtime_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
    1> C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\include\time.inl(112) : see declaration of ‘localtime’…

    Its a shame because i cant submit c++ in a text file that will compile with warnings, but i need a time-stamp on my log entries. If anyone can tell me how to modify this wonderful example code to be SAFE, that would be GREAT!

  5. It IS safe, assuming you’re not anticipating anyone attempting a buffer overflow on that specific function. If you aren’t worried about such a thing, just disable the CRT warnings. If you do decide to swap out the functions for their _s variant, then you’ll have to rewrite a good deal of the program; which, I suspect if you don’t understand why this is actually safe already, I suspect you lack the ability to do, so just disable the warnings.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>