Thread: Help, how to distill date from time_t value?

  1. #1
    Why bbebfe is not bbebfe? bbebfe's Avatar
    Join Date
    Nov 2008
    Location
    Earth
    Posts
    27

    Question Help, how to distill date from time_t value?

    This is my code below:
    Code:
    time_t now = time(NULL);
    printf("%s\n", ctime(&now));
    Its output is something like "Sat Dec 18 12:38:38 1971". I only want the date portion to be outputted, i.e. Dec 18 1971. Can anybody help me!

    Any help is appreciated!

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    strftime will take a struct tm and a format string (like printf sort of), which you can get by calling localtime or gmtime.

    Or you could just use sprintf() with the data in struct tm, since it gives you year, month, day, etc.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  3. #3
    Why bbebfe is not bbebfe? bbebfe's Avatar
    Join Date
    Nov 2008
    Location
    Earth
    Posts
    27
    Thank you so much!
    I put my code here to help others who need this two.
    Code:
    	char date_buff[40];
    	time_t time_value = time(NULL);
    	struct tm* my_tm = localtime(&time_value);
    	strftime(date_buff, sizeof(date_buff), "%b %d,%Y\n", my_tm); 
    	printf("%s\n", date_buff);
    NOTE: The returned pointer from localtime is a static variable, that means it might be overwritten by subsequent calls to ctime, gmtime, or localtime.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Advancing day by day until it matches a second date
    By nhubred in forum C++ Programming
    Replies: 1
    Last Post: 05-30-2009, 08:55 AM
  2. Checking array for string
    By Ayreon in forum C Programming
    Replies: 87
    Last Post: 03-09-2009, 03:25 PM
  3. Date program starts DOS's date
    By jrahhali in forum C++ Programming
    Replies: 1
    Last Post: 11-24-2003, 05:23 PM
  4. CDate Class - handle date manipulation simply
    By LuckY in forum C++ Programming
    Replies: 5
    Last Post: 07-16-2003, 08:35 AM

Tags for this Thread