Home > Enterprise >  What format specifier do I use in C for dates?
What format specifier do I use in C for dates?

Time:11-17

This is my code (I know using %d is wrong but I'm not sure what I am supposed to use):

#include <stdio.h>
#include <stdlib.h>
int main()
{
char charactername[] = "Ruby";
int age =18;
printf("Once upon a time there was girl named %s\n",charactername);
printf("%s was %d years old\n",charactername,age);

age =19;
int birthday = 22/07/2003;

printf("on %d she was born\n",birthday);
printf("On 22/07/2022 she will become %d",age);

return 0;
}

This is what the terminal gives me:

Once upon a time there was girl named Ruby

Ruby was 18 years old

on 0 she was born

On 22/07/2022 she will become 19

CodePudding user response:

You would use a combination of struct tm and strftime from time.h:

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

int main( void )
{
  struct tm bdate = { .tm_year=(2003 - 1900), .tm_mday = 22, .tm_mon = 6 };
  char datebuf[11] = {0};
  
  strftime( datebuf, sizeof datebuf, "%d/%m/%Y", &bdate );
  printf( "bdate = %s\n", datebuf );
  return 0;
}

Output:

$ ./bdate
bdate = 22/07/2003

CodePudding user response:

There is no "date" type built in to C. You can use strings for arbitray text; something like:

const char *birthday = "22/07/2003";

which you can print with a %s in the printf format

printf("on %s she was born\n",birthday);
  • Related