Click here to Skip to main content
15,888,286 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi everyone,

i was just wondering if I could use the system time and date for comparison and mathematical operations.

like if I input a date lets say January 3, 1996 and I compare it with the system Time
then the Age should be 19.

can someone tell me what to use and how to do it. kinda having a hard time understang how to get the values using time.h or ctime

thank you. :)
Posted
Updated 25-Feb-15 6:16am
v2
Comments
PIEBALDconsult 25-Feb-15 12:25pm    
DateTime minus DateTime yields TimeSpan
But you can't go directly from TimeSpan to months and years, because different months and years have different lengths.
So try DateTime.Year minus DateTime.Year , etc.
PIEBALDconsult 25-Feb-15 12:27pm    
See also: http://www.codeproject.com/Articles/343366/DateTime-Extensions-to-Make-Some-Simple-Tasks-a-Li

Time calculation is a wider area than you may imagine. Important: You have a global time ("UTC") and local time zones (offset to UTC). Look at a globe. Often times are seconds since 01.01.1970 0:00 o clock. I call it "unix start time".

Best start here C++ Date and Time.

Most frameworks like MFC (NSTime) or Apple (NSDate) have a lot of functions, but you must respect time zones. Write some examples and own classes to learn it.
 
Share this answer
 
For the trivial case that you present, the time functions are fairly easy to make use of. For anything much beyond this, be prepared to shed some tears..

Here's some code that will perform the calculation you mention.

Note that:
1. The value returned by time increments by 1 each second.
2. A value of 0 corresponds to Jan 1 1970 (the Unix Epoch)
3. I could have used difftime instead of performing the subtraction manually.

C++
#include <cstdio>
#include <ctime>

int main(int argc, char **argv)
{
    time_t now = time(NULL);
    tm birthDateTm = {0};

    birthDateTm.tm_year = 1996-1900;
    birthDateTm.tm_mon = 0;
    birthDateTm.tm_mday = 3;

    time_t birthTime = mktime(&birthDateTm);
    printf("BirthTime: %ld\n", birthTime);

    unsigned long dif = now - birthTime; //difftime(now, birthTime);


    unsigned long years = dif / (24 * 3600 * 7 * 52);
    printf("Elapsed time between %s and %s in years is: %ld\n", ctime(&birthTime), ctime(&now), years);
}



Output:
txt
BirthTime: 820591200
Elapsed time between Wed Jan 03 01:00:00 1996
 and Wed Jan 03 01:00:00 1996
 in years is: 19
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900