• C

How to convert a date in another format ?

Hi everybody,

just wanted your thoughts on the best way to convert a date from a format to another.

I currently have a date represented in m/d/yyyy and I need to convert it via a function to a yyyy/mm/dd format.

Thanks for your suggestions.
Who is Participating?

Improve company productivity with a Business Account.Sign Up

Kent OlsenConnect With a Mentor Data Warehouse Architect / DBACommented:
Hi The_Kingpin08,

There are countless ways to do this.  If you're that the input format is mm/dd/yy, then the easist is to use strtok() to split the strings.

If the format is m/d/yyyy, strtok() will do fine with a bit of help from atoi().

char OriginalDate[20] = "12/25/2004";
char *TempDate;
char NewDate[20];

char *Month, *Day, *Year;

  TempDate = strdup (OriginalDate);  /*  Make a temporary string that we can scribble into  */
  Month = strtok (TempDate, "/");
  Day = strtok (NULL, "/");
  Year = strtok (NULL, "");

  sprintf (NewDate, "%s/%s/%s", Year, Month, Day);

//if Month and/or Day can be a single digit, use this statement:

  sprintf (NewDate, "%s/%02d/%02d", Year, atoi(Month), atoi(Day));

Good Luck!
The_Kingpin08Author Commented:
Thanks a lot Kent.

Just 1 thinng, what does the printf does ?

Kent OlsenData Warehouse Architect / DBACommented:

There are several functions in the printf() family.  I used sprintf() to generate a string in a particular format.  Related functions like printf(), fprintf(), vfprintf(), etc all do basically the same thing, except that they take slightly different inputs and write to a string (sprintf), a file (fprintf), or the terminal (printf).

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.