Time conversion from 12hr to 24hr format in C

There will somewhat struggle while converting the time in the 24hr format in string array or pointer. But the solution provided here will be very simple and easy to understand to convert time in C

SAMPLE I/P

07:05:45PM

O/P

19:05:45

SOLUTION:

char* timeConversion(char* s) {           // s is a string pointer which contains time format
    if(*(s+8) == 'P'){
        int a = *(s+0) - 48;                         // integer a gets first digit in HR
        int b = *(s+1) - 48;                        // integer b gets second digit in HR
        int c = a*10 + b;                             // integer c is HR
        if(c!=12){
            c = c + 12;                                  // Now the conversion made and getting each hr digit
            b = c % 10;                                       individualy
            c = c / 10;
            a = c ;
        }
        *(s+0) = a + 48;
        *(s+1) = b + 48;
        *(s+8) = '\0';         
        *(s+9) = '\0';
        return s;
    }
    else{
        int a = *(s+0) - 48;
        int b = *(s+1) - 48;
        int c = a*10 + b;
        if(c==12){
            a=0;b=0;
        }
        *(s+0) = a + 48;
        *(s+1) = b + 48;
        *(s+8) = '\0';
        *(s+9) = '\0';
        return s;
    }
    return 0;
}

Comments

Popular Posts