#include #include #include #include #include #include #define PRE_FULL_YEAR 1 #define PRE_YEAR 2 #define PRE_MON 3 #define PRE_DAY 4 #define PRE_HOUR 5 int getPreType( char *str ) { if( strstr(str, "HH") != NULL ) { return PRE_HOUR; } else if( strstr(str, "DD") != NULL ) { return PRE_DAY; } else if( strstr(str, "MM") != NULL ) { return PRE_MON; } else if( strstr(str, "YY") != NULL ) { return PRE_YEAR; } return -1; } int replace( char *type, char *desc, char *tm ) { char *swit = NULL; if( (swit = strstr(desc, type)) != NULL ) { strncpy( swit, tm, strlen(tm) ); } return 0; } int getDate( int pre, char *str_tm) { struct tm when; time_t now, result; int pre_type; char yyyy[5]; char yy[3]; char mm[3]; char dd[3]; char hh[3]; memset( yyyy, 0, sizeof(yyyy) ); memset( yy, 0, sizeof(yy) ); memset( mm, 0, sizeof(mm) ); memset( dd, 0, sizeof(dd) ); memset( hh, 0, sizeof(hh) ); time( &now ); when = *localtime( &now ); if( (pre_type = getPreType(str_tm)) == -1 ) { return -1; } switch( pre_type ) { case PRE_HOUR : when.tm_hour = when.tm_hour - pre; break; case PRE_DAY : when.tm_mday = when.tm_mday - pre; break; case PRE_MON : when.tm_mon = when.tm_mon - pre; break; case PRE_YEAR : when.tm_year = when.tm_year - pre; break; default : when.tm_mday = when.tm_mday - pre; break; } if( (result = mktime( &when )) == (time_t)-1 ) { return -1; } sprintf( yyyy, "%04d", when.tm_year + 1900 ); sprintf( yy, "%02d", when.tm_year - 100 ); sprintf( mm, "%02d", when.tm_mon + 1 ); sprintf( dd, "%02d", when.tm_mday ); sprintf( hh, "%02d", when.tm_hour ); replace( "YYYY", str_tm, yyyy ); replace( "YY", str_tm, yy ); replace( "MM", str_tm, mm ); replace( "DD", str_tm, dd ); replace( "HH", str_tm, hh ); printf("%s", str_tm); return 0; } int main(int argc, char **argv) { if (argc == 3) { getDate( atoi(argv[2]), argv[1] ); } else { printf("Usage : %s [type] [pre]\n", argv[0]); printf("ex) 3 days ago\n %s YYYYMMDD 3\n", argv[0]); } return 0; }