Current date in filename

Hi, I'm trying to get the current date in my filename. Now I found a piece of code which should do it, but that does not give the right output. It looks like I need some kind of conversion ?

My code is:
void getFileName(){

DateTime now = RTC.now();

//filename[0] = (now.year()/1000)%10 + '0'; //To get 1st digit from year()
//filename[1] = (now.year()/100)%10 + '0'; //To get 2nd digit from year()
filename[0] = (now.year()/10)%10 + '0'; //To get 3rd digit from year()
filename[1] = now.year()%10 + '0'; //To get 4th digit from year()
filename[2] = now.month()/10 + '0'; //To get 1st digit from month()
filename[3] = now.month()%10 + '0'; //To get 2nd digit from month()
filename[4] = now.day()/10 + '0'; //To get 1st digit from day()
filename[5] = now.day()%10 + '0'; //To get 2nd digit from day()
Serial.println (filename);
}

The output I'm getting is : 65@5@500.CSV

This doesn't make sense, while the date is 21/5/19, so I would expect 21051900. Does anyone no what goes wrong ?

what's the filename[]variable definition ?

try this

#include <RTClib.h>
char filename[] = "DDMMYYYY.CSV";

void setup() {
  Serial.begin(115200);
  DateTime now = DateTime(2019, 05, 21, 12, 0, 0);

  filename[4] = '0' + (now.year() / 1000);
  filename[5] = '0' + (now.year() / 100) % 10;
  filename[6] = '0' + (now.year() / 10) % 10;
  filename[7] = '0' + (now.year() % 10);

  filename[2] = '0' + (now.month() / 10) % 10;
  filename[3] = '0' + (now.month() % 10);

  filename[0] = '0' + (now.day() / 10) % 10;
  filename[1] = '0' + (now.day() % 10);
  Serial.println(filename);
}

void loop() {}

Don't post snippets (Snippets R Us!)

please edit your post, select the code part and press the </> icon in the tool bar to mark it as code. It's unreadable as it stands. (also make sure you indented the code in the IDE before copying, that's done by pressing ctrlT on a PC or cmdT on a Mac)

It looks like your RTC is either not working or not being read correctly.
What kind of RTC do you have? How is it wired up? What RTC library (if any) are you using?
Please post your entire sketch.

Thanks for your reply.

I found the problem. The RTC was not started yet.

I got it working now by putting "Wire.begin();" before the file creation, now it works fine.

1 Like

Thanks for letting us know. You can close it.

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.