I have this code in the setup for my Arduino to create a filename using the date. It is working however there is a problem.
#include <DS3231.h>
#include <SD.h>
#include <SPI.h>
#include <dht.h>
dht DHT;
Time now;
int dt;
int t;
unsigned int interation = 1;
char filename[12];
DS3231 rtc(SDA, SCL);
void setup() {
Serial.begin(9600);
rtc.begin(); // Initialize the rtc object
rtc.setDOW(THURSDAY); // Set Day-of-Week to SUNDAY
rtc.setTime(21, 48, 0); // Set the time to 12:00:00 (24hr format)
rtc.setDate(10, 11, 2017); // Set the date to January 1st, 2014
now = rtc.getTime();
String(String(now.year) + String(now.mon) + String(now.dow) + ".csv").toCharArray(filename, 12);
Serial.println(filename);
It is printing a string of the date but there is no leading zero in the month digit when it is a single digit.
The code prints this 2017111.csv instead of 20170111.csv. How can I fix this?
You need an if statement to test if the number is less than 10 and if so add your own 0.
String myMonthString = "";
int mon = now.mon;
if(mon < 10){
myMonthString += '0';
}
myMonthString += mon;
A far more elegant solution would be to use sprintf. This also doesn't use the String class which can do some bad things on little microcontrollers and is generally to be avoided on Arduino.
char fileName[12];
sprintf(fileName, "%d%02d%02d.csv", now.year, now.mon, now.dow);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With