Like Tree1Likes
  • 1 Post By Salem

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

This is a discussion on How to print time in yyyy:mm:dd format? within the C Programming forums, part of the General Programming Boards category; I know it has something to do with time.h, but I'm not familiar with using that header's functions. Right now ...

  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
    32,848
    rags_to_riches likes this.
    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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  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
    32,848
    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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 1
    Last Post: 07-15-2011, 11:46 AM
  2. How to format print for Hex like output
    By Teropita in forum C Programming
    Replies: 2
    Last Post: 05-07-2011, 07:59 PM
  3. OLE date and time format
    By pastitprogram in forum C++ Programming
    Replies: 7
    Last Post: 04-05-2008, 04:46 PM
  4. printing time in HH:MM:SS:MS format
    By msenthil in forum Linux Programming
    Replies: 3
    Last Post: 10-24-2007, 02: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


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21