Go Down

Topic: Formatting the Date & Time info? (Read 361 times) previous topic - next topic

coding1227

Hi everyone

I am trying to print the  current date & time using a chronodot v2, but what I would like it to format the date & time info with a "0" whenever a date and/or time is less than 10. For instance, I would like the arduino to print the information from this:
2/22/2013 5:3:6

to something like this:
02/22/2013 05:03:06

Is this possible to do? Here's what I've been able to work with so far:

Code: [Select]

// Lets load the libraries needed:

#include <Wire.h>
#include "RTClib.h"

RTC_DS1307 RTC;


//load the settings and call the libraries to be used:
void setup () {
  Serial.begin(9600);
  Wire.begin();
  RTC.begin();


  if (! RTC.isrunning()) {
    Serial.println("RTC is NOT running!");
    // following line sets the RTC to the date & time this sketch was compiled
    RTC.adjust(DateTime(__DATE__, __TIME__));
  }
}


void loop () {
  //Time stuff
  DateTime now = RTC.now();

  Serial.print(now.month(), DEC);
  Serial.print('/');
  Serial.print(now.day(), DEC);
  Serial.print('/');
  Serial.print(now.year(), DEC);
  Serial.print(' ');
  Serial.print(now.hour(), DEC);
  Serial.print(':');
  Serial.print(now.minute(), DEC);
  Serial.print(':');
  Serial.print(now.second(), DEC);
  Serial.println(" ");

  delay(1000);

}

PeterH

The easiest way would be to format the date/time to a string and print that. There is a family of print functions that do this, and snprintf is the one you want to use in this case:

Code: [Select]

char buffer[32]; //make this big enough to hold the resulting string

snprintf(buffer, sizeof(buffer), "%02d/%02d/%4d %02d:%02d:%02d", now.month(), now.day(), now.year(), now.hour(), now.minute(), now.second());

//buffer now contains a string like 02/22/2013 05:03:06

Serial.print(buffer);
I only provide help via the forum - please do not contact me for private consultancy.

coding1227

Hey PeterH

thank you so much for the reply... this makes total sense. I tried your suggestion and it works flawlessly :)

Go Up
 


Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

Arduino
via Egeo 16
Torino, 10131
Italy