LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   How to print out "n" days ago's year, month and day? (https://www.linuxquestions.org/questions/programming-9/how-to-print-out-n-days-agos-year-month-and-day-861920/)

ArthurHuang 02-10-2011 05:41 PM

How to print out "n" days ago's year, month and day?
 
Interesting uh?
For example, 2 days ago's date is 2011 Feb 8th.
This is not a homework...

thanks!

ta0kira 02-10-2011 06:51 PM

Code:

date -d '2 days ago'
Kevin Barry

Nominal Animal 02-10-2011 07:22 PM

I was just going to write what ta0kira wrote. The GNU date command is awesome. Anyway, in C, you can do
Code:

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

int main(void)
{
    time_t    now, then;
    struct tm *split;

    /* Get the current time */
    now = time(NULL);

    /* Convert the time to broken-down format */
    split = localtime(&now);

    /* Substract two days -- it is okay to go out of valid range */
    split->tm_mday -= 2;

    /* Renormalize the broken-down format, and return the time then. */
    then = mktime(split);
   
    printf("Two days ago was %04d-%02d-%02d, or %s\n",
          split->tm_year + 1900, split->tm_mon + 1, split->tm_mday,
          ctime(&then));

    return 0;
}

This uses the local time as a basis. If you need UTC, use gmtime instead of locatime.

The call to mktime both normalizes the split date, and returns the resulting time in the base time_t format, seconds since epoch. See the ctime, localtime, and mktime man page for details. This is in the POSIX standard, and should work as-is on all sane operating systems.

It shouldn't be too difficult to add parameter parsing to the above, to get exactly what you need.
Nominal Animal

kurumi 02-10-2011 08:33 PM

Code:

$ ruby -r'date' -e 'print (DateTime.now - 48/24).strftime("%Y/%m/%d")'


All times are GMT -5. The time now is 09:19 AM.