• Sharing utility to set year

    From Dave Brower@21:1/5 to All on Fri Jan 8 16:04:52 2016
    If you've got one of these, you've no doubt found that date(1) doesn't work in the new millenium to set the time. You set the time part with date, then fudge the year with this program.

    Don't remember who I stole most of it from, or what if anything I wrote myself when I previously used in in 2012.

    -dB

    ---------- snip year.c ----------

    # include <time.h>
    # include <sys/types.h>
    # include <stdio.h>


    /* Return 1 if `y' is a leap year, 0 otherwise.
    */

    static int leap (y) int y; {
    if (y % 400 == 0)
    return (1);
    if (y % 100 == 0)
    return (0);
    return (y % 4 == 0);
    }

    /* Return the number of days between Jan 1, 1970 and the given
    * broken-down time.
    */

    static int ndays (p) struct tm *p; {
    int n = p->tm_mday;
    int m, y;
    char *md = "\37\34\37\36\37\36\37\37\36\37\36\37";

    for (y = 1970; y < p->tm_year; ++y) {
    n += 365;
    if (leap (y)) ++n;
    }
    for (m = 0; m < p->tm_mon; ++m)
    n += md[m] + (m == 1 && leap (y));
    return (n);
    }

    /* Convert a broken-down time (such as returned by localtime())
    * back into a `time_t'.
    */

    time_t mktime (tp) struct tm *tp; {
    int m1, m2;
    time_t t;
    struct tm otm;

    t = (ndays (tp) - 1) * 86400L + tp->tm_hour * 3600L
    + tp->tm_min * 60 + tp->tm_sec;
    /*
    * Now the hard part -- correct for the time zone:
    */
    otm = *tp;
    tp = localtime (&t);
    m1 = tp->tm_hour * 60 + tp->tm_min;
    m2 = otm.tm_hour * 60 + otm.tm_min;
    t -= ((m1 - m2 + 720 + 1440) % 1440 - 720) * 60L;
    return (t);
    }


    int main( argc, argv )
    int argc;
    char **argv;
    {
    int rv;
    time_t t;
    struct tm *tm;
    char buf[ 64 ];
    char *p;

    if( argc < 2 )
    {
    printf("usage: year nnnn\n");
    exit( 1 );
    }


    time((time_t*)&t);
    p = ctime(&t);
    printf("time %u %p\n", t, p );

    tm = localtime( &t );
    printf("localtime of tm is %s\n", asctime(tm) );


    tm->tm_year = atoi( argv[1] );

    printf("changing year to %d, %s\n", tm->tm_year, asctime(tm) );

    t = mktime( tm );

    printf("new time will be %d, %s\n", t, ctime(&t) );

    rv = stime( &t );
    if( rv < 0 )
    perror("stime");

    return 0;
    }

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)