Thread: How to print time in yyyy:mm:dd format?

  1. #1
    Registered User
    Join Date
    Mar 2012
    Posts
    26

    Question How to print time in yyyy:mm:dd format?

    I know it has something to do with time.h, but I'm not familiar with using that header's functions. Right now I have:

    Code:
        time_t TimeNow = time(NULL);
        struct tm *tm = localtime(&TimeNow);
        printf("%d:%d:%d", tm->tm_year, tm->tm_mon, tm->tm_mday);
    It compiles, but it gives me this:

    112:2:25

    The month and day make sense, but they're lacking the preceding 0s. The year just doesn't make any sense.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Mar 2012
    Posts
    26
    This works, but is this good, syntax-wise?

    Code:
    time_t t;    struct tm* tm;
        char Date[11], Time[11];
        
        time(&t);
        tm = localtime(&t);
        
        strftime(Date, sizeof Date, "%Y:%m:%d", tm);
        strftime(Time, sizeof Time, "%I:%M:%S", tm);
        printf("%s ", Date);
        printf("%s", Time);

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    Looks OK.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 1
    Last Post: 07-15-2011, 10:46 AM
  2. How to format print for Hex like output
    By Teropita in forum C Programming
    Replies: 2
    Last Post: 05-07-2011, 06:59 PM
  3. OLE date and time format
    By pastitprogram in forum C++ Programming
    Replies: 7
    Last Post: 04-05-2008, 03:46 PM
  4. printing time in HH:MM:SS:MS format
    By msenthil in forum Linux Programming
    Replies: 3
    Last Post: 10-24-2007, 01:03 PM
  5. How to read in time format?
    By witchiz brews in forum C Programming
    Replies: 1
    Last Post: 02-12-2006, 02:10 AM

Tags for this Thread