Home > Software engineering >  Save the date of today in a string
Save the date of today in a string

Time:11-05

I want to save the date of today in a string and have the following code with the following output:

Code:

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

int main()
{
  time_t t = time(NULL);
  struct tm tm = *localtime(&t);
  printf("d-d", tm.tm_mday, tm.tm_mon   1);
  printf("\n");
}

Output (for today, November the 5th):

05-11

What is the easiest way to save 05-11 in a string?

CodePudding user response:

You can use the standard strftime function (declared in "time.h"), which takes a variety of format specifiers (akin to those used in printf) to extract and format the various date and/or time fields of a struct tm.

In your case, you would use the %d and %m specifiers to get the (two-digit) day and month numbers:

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

int main()
{
    char StrDate[8];
    time_t t = time(NULL);
    strftime(StrDate, sizeof(StrDate), "%d-%m", localtime(&t));
    printf("%s\n", StrDate);
    return 0;
}

You could even add the newline character to the StrDate buffer directly, by appending the %n format specifier.

CodePudding user response:

I used sprintf() which worked fine for me

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

int main()
{
  time_t t = time(NULL);
  struct tm tm = *localtime(&t);
  char str[80];

  sprintf(str, "d-d", tm.tm_mday, tm.tm_mon   1);
  printf("%s", str);
  printf("\n");
}


  • Related